3

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 i.e.

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)

4

5 に答える 5

8

set(list1).difference(set(list2))

于 2010-02-11T12:48:17.090 に答える
6

セットを使用して、リスト間の違いを取得します。

>>> list1 = ['one','two','three','four','five']
>>> list2 = ['one','two','four']
>>> set(list1) - set(list2)
set(['five', 'three'])
于 2010-02-11T12:48:07.960 に答える
1

set.difference:

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

list2から setへの変換をスキップできます。

于 2010-02-11T12:52:55.867 に答える
0

セットまたはリスト内包表記でそれを行うことができます:

unused = [i for i in list1 if i not in list2]
于 2010-02-11T12:49:59.400 に答える
0

ここでの答えはすべて正しいです。リストが短い場合は、リスト内包表記を使用します。セットの方が効率的です。コードが機能しない理由を調べてみると、エラーは発生しません。(うまくいきませんが、それは別の問題です)。

>>> 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ステートメントが意味をなさないことです。お役に立てれば。

于 2010-02-11T13:01:28.870 に答える