这是我的代码:
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
进行比较,并打印出与 item
不同的数字。
我可以打印出在比较时属于z
而不是item
的元素,但是使用上面的代码尝试相反的操作时没有任何输出。
有什么帮助吗?
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
首先会从列表中删除除一个外的所有重复元素。 - VDV>> items = [1,2,3,4]
>> Z = [3,4,5,6]
>> print list(set(items)-set(Z))
[1, 2]
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]
list1 = [1,2,3,4]; list2 = [0,3,3,6]
print set(list2) - set(list1)
>>> 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])
#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
正如其他答案所述,您可能希望尝试使用集合(set)。
http://docs.python.org/tutorial/controlflow.html#for-statements
我认为你的困惑源于使用了变量名“item”两次,分别表示两个不同的含义。items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
z = [3, 4, 5, 6]
set_z = set(z)
result = [e for e in items if e not in set_z]
result
包含:[0, 1, 2, 7, 8, 9]
你正在通过迭代 z 来重新分配 item 的值。因此,在 for 循环中第一次,item = 0,下一个 item = 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