查找不在列表中的元素


69

所以这是我的代码:

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相比时item

z当不比较时,我可以打印其中的元素item,但是当我尝试使用上面的代码做相反的操作时,则什么也不会打印。

有什么帮助吗?


这回答了你的问题了吗?得到两个列表之间的差异
乔治

Answers:


175

您的代码没有按照我认为的方式执行。该行将for item in z:遍历z,每次item等于的一个元素zitem因此,在执行任何操作之前,原始列表将被覆盖。

我想你想要这样的东西:

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)

4
set如果检查的列表包含非唯一元素,则使用将无法正常工作,因为set首先会从列表中删除所有出现的非唯一元素(除了一次)。
VDV


18

使用列表理解:

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}

vs列表理解如上

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]

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

print set(list2) - set(list1)

4

如果运行一个循环,从z中获取项目,您如何期望它们不在z中?恕我直言,将来自不同列表的项目与z进行比较会更有意义。


4

不,z是不确定的。项目包含一个整数列表。

我认为您要执行的操作是:

#z defined elsewhere
item = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

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

如其他答案中所述,您可能想尝试使用集合。


3
>>> item = set([0,1,2,3,4,5,6,7,8,9])
>>> z = set([2,3,4])
>>> print item - z
set([0, 1, 5, 6, 7, 8, 9])

3

您的代码是禁止操作的。根据循环的定义,“ item”必须在Z中。Python中的“ For ... in”循环表示“循环,尽管列表名为'z',但每次循环时,请给我下一个列表,并将其称为“ item””

http://docs.python.org/tutorial/controlflow.html#for-statements

我认为您感到困惑的原因是,您两次使用了变量名“ item”来表示两种不同的含义。


1

在遍历z时,您正在将item重新分配给z中的值。因此,在您的for循环中,第一次= 0,下一个= 1,依此类推...您永远不会将一个列表与另一个列表进行比较。

要非常明确地执行此操作:

>>> item = [0,1,2,3,4,5,6,7,8,9]
>>> z = [0,1,2,3,4,5,6,7]
>>> 
>>> for elem in item:
...   if elem not in z:
...     print elem
... 
8
9

1

itemz排序迭代器的情况下,我们可以通过执行以下操作将复杂度从降低O(n^2)O(n+m)

def iexclude(sorted_iterator, exclude_sorted_iterator):
    next_val = next(exclude_sorted_iterator)
    for item in sorted_iterator:
        try:
            while next_val < item:
                next_val = next(exclude_sorted_iterator)
                continue
            if item == next_val:
                continue
        except StopIteration:
            pass
        yield item

如果这两个是迭代器,我们还可以减少不将zexclude_sorted_iterator)作为列表存储的内存占用。


for循环(其被批准的答案):好大哦是O(n)和你的答案有嵌套循环一段时间在循环,使复杂性会在你的情况下,这是增加O(n^2)
穆罕默德汗Haseeb
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.