迭代通过所有listA的项目不会出现在数组listB
new_list = set(LISTA) - set(LISTB) # if you don't have duplicate
for i in new_list:
print i
或者:
for i in LISTA:
if i in LISTB:
continue
print i
我只能在几分钟内注册,但这个列表减法解决了我的问题。谢谢。 – relima 2010-10-25 00:46:13
如果您不需要保留重复项,那么设置非常棒。另外可能很重要的一点是'new_list'不是一个列表。 – 2010-10-25 00:58:09
集也失去了订购。一般来说,有效的做法是只为'listb'创建一个集合,其中排序和重复从不重要,所以'我在listb'中是有效的。 – 2010-10-25 05:11:39
for i in LISTA:
if i not in LISTB:
print i
一个更复杂的解决方案。这是一个简单的交点补充。
a = set([1, 2, 3])
b = set([3, 4, 5])
print(a - b)
+1一个非常干净的解决方案。 – Xorlev 2010-10-25 00:57:20
for i in (i for i in LISTA if i not in LISTB):
print i
的部分括号中是一个generator expression。这比其他方法的好处是,它不会创建重复(临时)集或列表对象。如果LISTA和/或LISTB真的很大,这一点尤其重要。
我不确定这里最好的语法,但你可以嵌套一个如果 – Orbit 2010-10-25 00:43:45
请用[家庭作业]标记标记你的家庭作业。 – 2010-10-25 10:17:12
抱歉让你失望S.lott,这里没有作业。 – relima 2010-10-25 14:17:38