[英]How do you compare three lists and add the duplicates to one list and the non-duplicates to another list?
I need to devise a way to compare all of the numbers in the three lists and should a number be present in all three lists - I have to add it to the matching_numbers list.我需要 devise 一种方法来比较三个列表中的所有数字,并且如果所有三个列表中都存在一个数字 - 我必须将它添加到 match_numbers 列表中。 If a number doesn't match any of the other numbers, then I have to add it to the unique_numbers list.如果一个数字与任何其他数字都不匹配,那么我必须将它添加到 unique_numbers 列表中。 I tried using a for loop, but I was only able to complete half of the equation and I wasn't sure as to how I could add all the unmatching numbers to the unique_numbers list.我尝试使用 for 循环,但我只能完成等式的一半,而且我不确定如何将所有不匹配的数字添加到 unique_numbers 列表中。 I also don't want any duplicates in my matching_numbers or unique_numbers list.我也不希望我的 matching_numbers 或 unique_numbers 列表中有任何重复项。
list_1 = []
list_2 = []
list_3 = []
matching_numbers = []
unique_numbers = []
countone = 0
counttwo = 0
countthree = 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, 50)
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, 50)
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, 50)
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 =
This is the type of thing that Sets
are perfect for.这是Sets
最适合的类型。 Unlike a list, where checking if something is present has a compexity of O(n)
, set lookups are O(1)
.与列表不同,检查是否存在的复杂性为O(n)
,集合查找为O(1)
。 Also, sets have methods already to check for intersections, differences, etc. So items in three sets can be computed as the intersection of the three:此外,集合已经具有检查交叉点、差异等的方法。因此,三个集合中的项目可以计算为三个集合的交叉点:
all_numbers = set_1 | set_2 | set_3
matching_numbers = set_1 & set_2 & set_3
unique_numbers = all_numbers - matching_numbers
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.