【发布时间】:2022-01-22 15:37:37
【问题描述】:
x =[1,2,3,4,5,6]
y = [1,2,3,4,5]
if x == y:
print("Numbers found")
else:
print("Numbers not found")
我想打印列表 y 中不存在的数字。
【问题讨论】:
x =[1,2,3,4,5,6]
y = [1,2,3,4,5]
if x == y:
print("Numbers found")
else:
print("Numbers not found")
我想打印列表 y 中不存在的数字。
【问题讨论】:
最快的方法是在集合中转换并打印差异:
>>> print(set(x).difference(set(y)))
{6}
此代码打印存在于x 但不在y 中的数字
【讨论】:
你可以这样做:
x = [1,2,3,4,5,6]
y = [1,2,3,4,5]
for i in x:
if i not in y:
print(i)
【讨论】:
x =[1,2,3,4,5,6]
y = [1,2,3,4,5]
for i in x:
if i in y:
print(f"{i} found")
else:
print(f"{i} not found")
【讨论】:
我认为这是最好的选择。
x =[1,2,3,4,5,6]
y = [1,2,3,4,5]
for number in x:
if number not in y:
print(f"{number} not found")
【讨论】:
获取不匹配:
def returnNotMatches(a, b):
return [[x for x in a if x not in b], [x for x in b if x not in a]]
或
new_list = list(set(list1).difference(list2))
获得交点:
list1 =[1,2,3,4,5,6]
list2 = [1,2,3,4,5]
list1_as_set = set(list1)
intersection = list1_as_set.intersection(list2)
输出:
{1, 2, 3, 4, 5}
您也可以将其转移到列表中:
intersection_as_list = list(intersection)
或:
new_list = list(set(list1).intersection(list2))
【讨论】: