简体   繁体   中英

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:

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 :

>>> list1 = ['one','two','three','four','five']
>>> list2 = ['one','two','four']
>>> set(list1).difference(list2)
{'five', 'three'}

you can skip conversion of list2 to 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. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM