查找不在列表中的元素

96 投票
12 回答
279794 浏览
提问于 2025-04-15 18:15

这是我的代码:

item = [0,1,2,3,4,5,6,7,8,9]
z = []  # list of integers

for item in z:
    if item not in z:
        print item

z 是一个整数列表。我想把 itemz 进行比较,打印出那些在 z 中找不到的数字。

我可以打印出那些在 z 中的元素,但当我尝试用上面的代码做相反的事情时,什么都没有打印出来。

有人能帮帮我吗?

12 个回答

23

使用列表推导式:

print [x for x in item if x not in Z]

或者使用过滤函数:

filter(lambda x: x not in Z, item)

如果你用set,可能会出现问题,特别是当你检查的列表里有重复的元素时,比如:

print item

Out[39]: [0, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print Z

Out[40]: [3, 4, 5, 6]

set(item) - set(Z)

Out[41]: {0, 1, 2, 7, 8, 9}

和上面提到的列表推导式相比

print [x for x in item if x not in Z]

Out[38]: [0, 1, 1, 2, 7, 8, 9]

或者过滤函数:

filter(lambda x: x not in Z, item)

Out[38]: [0, 1, 1, 2, 7, 8, 9]
73
>> items = [1,2,3,4]
>> Z = [3,4,5,6]

>> print list(set(items)-set(Z))
[1, 2]

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

216

你的代码并没有像你想的那样工作。那行 for item in z: 是在遍历 z,每次都会把 item 设置为 z 中的一个元素。所以,原来的 item 列表在你还没做任何事情之前就被覆盖了。

我觉得你可能想要的是这样的:

item = [0,1,2,3,4,5,6,7,8,9]

for element in item:
    if element not in z:
        print(element)

不过你也可以简单地这样做:

[x for x in item if x not in z]

或者(如果你不介意丢失重复的非唯一元素):

set(item) - set(z)

撰写回答