在Python中的另一个列表比较列表项值与其它物品
题
我想在一个列表中的值在第二列表进行比较的值,并将所有那些在第一个列表中,但不是在第二即。
list1 = ['one','two','three','four','five']
list2 = ['one','two','four']
将返回 '三' 和 '5'。
我只有与Python的一点经验,所以这可能变成是一个荒谬和愚蠢的方式来试图解决这个问题,但是这是我迄今所做的:
def unusedCategories(self):
unused = []
for category in self.catList:
if category != used in self.usedList:
unused.append(category)
return unused
然而,这会引发错误“迭代优于非序列”,这是我收集为意指一个或两个名单'是实际上没有列出(原始输出两者是相同的格式,我的第一个例子)
解决方案
使用设置来获取列表之间的差:
>>> list1 = ['one','two','three','four','five']
>>> list2 = ['one','two','four']
>>> set(list1) - set(list2)
set(['five', 'three'])
其他提示
set(list1).difference(set(list2))
与 set.difference
:
>>> list1 = ['one','two','three','four','five']
>>> list2 = ['one','two','four']
>>> set(list1).difference(list2)
{'five', 'three'}
可以跳过list2
设置的转换。
您可以用集或列表理解做到这一点:
unused = [i for i in list1 if i not in list2]
这里所有的答案是正确的。我会使用列表中理解,如果列表是短;套效率会更高。在探讨为什么你的代码不能正常工作,我没有得到这个错误。 (它不工作,但是这是一个不同的问题)。
>>> list1 = ['a','b','c']
>>> list2 = ['a','b','d']
>>> [c for c in list1 if not c in list2]
['c']
>>> set(list1).difference(set(list2))
set(['c'])
>>> L = list()
>>> for c in list1:
... if c != L in list2:
... L.append(c)
...
>>> L
[]
问题是,if
说法是没有意义的。
希望这有助于。
不隶属于 StackOverflow