Python 如何比较三个列表,并将重复列表添加到一个列表中,将非重复列表添加到另一个列表中?
我需要设计一种方法来比较三个列表中的所有数字,如果三个列表中都有一个数字,我必须将其添加到匹配的数字列表中。如果一个数字与其他任何数字都不匹配,那么我必须将其添加到唯一的数字列表中。我尝试使用for循环,但我只能完成一半的等式,我不确定如何将所有不匹配的数字添加到唯一的_数字列表中。我也不希望我的匹配号码或唯一号码列表中有任何重复项Python 如何比较三个列表,并将重复列表添加到一个列表中,将非重复列表添加到另一个列表中?,python,python-3.x,list,concatenation,Python,Python 3.x,List,Concatenation,我需要设计一种方法来比较三个列表中的所有数字,如果三个列表中都有一个数字,我必须将其添加到匹配的数字列表中。如果一个数字与其他任何数字都不匹配,那么我必须将其添加到唯一的数字列表中。我尝试使用for循环,但我只能完成一半的等式,我不确定如何将所有不匹配的数字添加到唯一的_数字列表中。我也不希望我的匹配号码或唯一号码列表中有任何重复项 list_1 = [] list_2 = [] list_3 = [] 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 =
这是一种非常适合你的东西。与列表不同,在列表中,检查是否存在某个内容的compexity为
O(n)
,设置查找为O(1)
。此外,集合已经有了检查交点、差异等的方法。因此,三个集合中的项目可以计算为三个集合的交点:
all_numbers = set_1 | set_2 | set_3
matching_numbers = set_1 & set_2 & set_3
unique_numbers = all_numbers - matching_numbers
这在三组数据中找不到唯一的数字。考虑三个SETY1:{ 7 },SETIG2:{ 9 },SETY3: { 7 }。代码>匹配的\u编号将为空,
唯一的\u编号
将为{7,9}
,这是不正确的,因为7分为两组。OP的要求没有说明应如何处理重复项;我认为set实现更正确,但谁知道需要什么。我想我读到了如果一个数字与其他任何数字都不匹配,那么我必须将其添加到唯一数字列表中。
意味着唯一数字中的数字将是全局唯一的。