[英]Comparing list item values to other items in other list in Python
I want to compare the values in one list to the values in a second list and return all those that are in the first list but not in the second ie 我想将一个列表中的值与第二个列表中的值进行比较,并返回第一个列表中但不在第二个列表中的所有值。
list1 = ['one','two','three','four','five']
list2 = ['one','two','four']
would return 'three' and 'five'. 将返回'三'和'五'。
I have only a little experience with python, so this may turn out to be a ridiculous and stupid way to attempt to solve it, but this what I have done so far: 我对python只有一点经验,所以这可能会成为一种荒谬而愚蠢的尝试解决方法,但这就是我迄今所做的:
def unusedCategories(self):
unused = []
for category in self.catList:
if category != used in self.usedList:
unused.append(category)
return unused
However this throws an error 'iteration over non-sequence', which I gather to mean that one or both 'lists' aren't actually lists (the raw output for both is in the same format as my first example) 然而,这会引发错误'迭代超过非序列',我认为这意味着一个或两个'列表'实际上不是列表(两者的原始输出与我的第一个示例的格式相同)
set(list1).difference(set(list2))
Use sets to get the difference between the lists: 使用集合来获取列表之间的差异:
>>> list1 = ['one','two','three','four','five']
>>> list2 = ['one','two','four']
>>> set(list1) - set(list2)
set(['five', 'three'])
with set.difference
: with
set.difference
:
>>> list1 = ['one','two','three','four','five']
>>> list2 = ['one','two','four']
>>> set(list1).difference(list2)
{'five', 'three'}
you can skip conversion of list2
to set. 你可以跳过
list2
到set的转换。
你可以用集合或列表理解来做到这一点:
unused = [i for i in list1 if i not in list2]
All the answers here are correct. 这里的所有答案都是正确的。 I would use list comprehension if the lists are short;
如果列表很短,我会使用列表理解; sets will be more efficient.
套装会更有效率。 In exploring why your code doesn't work, I don't get the error.
在探索为什么你的代码不起作用时,我没有得到错误。 (It doesn't work, but that's a different issue).
(它不起作用,但这是一个不同的问题)。
>>> 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
[]
The problem is that the if
statement makes no sense. 问题是
if
语句没有意义。 Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.