查找不在列表中的元素

Dav*_*ave 61 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
Run Code Online (Sandbox Code Playgroud)

Z包含整数列表.我想将项目与Z进行比较,并打印出与项目相比时不在Z中的数字.我可以打印Z中的elemtens,当比较不是项目时,但当我尝试使用上面的代码执行相反的操作时,没有打印.

有帮助吗?

ezo*_*zod 148

你的代码没有做我认为你认为它正在做的事情.该行将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
Run Code Online (Sandbox Code Playgroud)

但你可以很容易地这样做:

[x for x in item if x not in z]
Run Code Online (Sandbox Code Playgroud)

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

set(item) - set(z)
Run Code Online (Sandbox Code Playgroud)

  • 如果检查的列表包含非唯一元素,则使用`set`将无法正常工作,因为`set`将首先从列表中删除除非出现的非唯一元素. (4认同)

Ant*_*ins 52

>> items = [1,2,3,4]
>> Z = [3,4,5,6]

>> print list(set(items)-set(Z))
[1, 2]
Run Code Online (Sandbox Code Playgroud)


VDV*_*VDV 11

使用列表理解:

print [x for x in item if x not in Z]
Run Code Online (Sandbox Code Playgroud)

或使用过滤功能:

filter(lambda x: x not in Z, item)
Run Code Online (Sandbox Code Playgroud)

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}
Run Code Online (Sandbox Code Playgroud)

vs列表理解如上

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

Out[38]: [0, 1, 1, 2, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)

或过滤功能:

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

Out[38]: [0, 1, 1, 2, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)


jsp*_*cal 9

list1 = [1,2,3,4]; list2 = [0,3,3,6]

print set(list2) - set(list1)
Run Code Online (Sandbox Code Playgroud)