python - 查找不在列表中的元素

标签 python list

这是我的代码:

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 并打印出与 item 比较时不在 z 中的数字。

当与 item 相比时,我可以打印 z 中的元素,但是当我尝试使用上面的代码执行相反操作时,什么都不会打印。

有什么帮助吗?

最佳答案

您的代码并没有像我认为的那样做。 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)

关于python - 查找不在列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2104305/

相关文章:

Python线程类调用另一个线程类(队列帮助)

python - 按组计算连续重复项

python - 南方不承认新型号

c# - 在 C# 中使用 LINQ 提取 List<T> 的两个属性

html - html中的异常空格

python - 使用 while 循环从输入创建列表

python - cgi.FieldStorage 类如何处理文件上传?

python - 使用python将文本文件(对象)作为.txt插入到excel表的单元格中

python - 将字典中的键同步到列表中的多个值

java - 想要列表中的非重复元素