我能够找到一种方法来比较三个列表中的所有数字。如果所有三个列表中都存在一个数字,则必须将其添加到matching_numbers列表中。如果一个数字与其他任何数字都不匹配,那么我将不得不将其添加到unique_numbers列表中。在三个列表中的两个列表中找到的重复项被视为唯一编号,因此应将其放入unique_numbers列表中。
list_1 = []
list_2 = []
list_3 = []
matching_numbers = []
unique_numbers = []
countone = 0
counttwo = 0
countthree = 0
exit = 0
import random
name = input("Hello USER. What will your name be?")
print("Hello " + name + ". Welcome to the NUMBERS program.")
amountone = int(input("How many numbers do you wish to have for your first list? Please choose from between 1 and 15."))
while countone != amountone:
x = random.randint(1, 30)
list_1 += [x,]
print(list_1)
countone += 1
amounttwo = int(input("For your second list, how many numbers do you wish to have? Please choose from between 1 and 15."))
while counttwo != amounttwo:
x = random.randint(1, 30)
list_2 += [x,]
print(list_2)
counttwo += 1
amountthree = int(input("For your third list, how many numbers do you wish to have? Please choose from between 1 and 15."))
while countthree != amountthree:
x = random.randint(1, 30)
list_3 += [x,]
print(list_3)
countthree += 1
for a in list_1:
for b in list_2:
for c in list_3:
if a == b and b == c:
matching_numbers = list(set(list_1) & set(list_2) & set(list_3))
else:
unique_numbers =
仅使用列表方法,(您也可以使用集合或collections.Counter
),您可以执行以下操作:
def separate(*lists):
unique_values = []
duplicate_values = []
for list_ in lists:
for value in list_:
if all(value in l for l in lists):
if value not in duplicate_values:
duplicate_values.append(value)
else:
if value not in unique_values:
unique_values.append(value)
return unique_values, duplicate_values
我鼓励您尝试使用集合重写此代码,以了解它们如何使此代码更快,更简单。
尝试使用集:
import random
list_1 = [random.randint(0, 30) for _ in range(30)]
list_2 = [random.randint(0, 30) for _ in range(30)]
list_3 = [random.randint(0, 30) for _ in range(30)]
matched_numbers =set.union(set(list_1).intersection(set(list_2)), set(list_1).intersection(set(list_3)), set(list_2).intersection(set(list_3)))
unique_numbers = set.difference(set.union(set(list_1), set(list_2), set(list_3)), matched)