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))