所以这是我的代码:
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
包含一个整数列表。我想比较item
于z
并打印出不在的数字z
相比时item
。
z
当不比较时,我可以打印其中的元素item
,但是当我尝试使用上面的代码做相反的操作时,则什么也不会打印。
有什么帮助吗?
Answers:
您的代码没有按照我认为的方式执行。该行将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)
set
如果检查的列表包含非唯一元素,则使用将无法正常工作,因为set
首先会从列表中删除所有出现的非唯一元素(除了一次)。
使用列表理解:
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]
您的代码是禁止操作的。根据循环的定义,“ item”必须在Z中。Python中的“ For ... in”循环表示“循环,尽管列表名为'z',但每次循环时,请给我下一个列表,并将其称为“ item””
http://docs.python.org/tutorial/controlflow.html#for-statements
我认为您感到困惑的原因是,您两次使用了变量名“ item”来表示两种不同的含义。
在item
和z
排序迭代器的情况下,我们可以通过执行以下操作将复杂度从降低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
如果这两个是迭代器,我们还可以减少不将z
(exclude_sorted_iterator
)作为列表存储的内存占用。
O(n)
和你的答案有嵌套循环一段时间在循环,使复杂性会在你的情况下,这是增加O(n^2)