47

重複の可能性:
Python で 2 つのリストから違いを取得する

これを行う簡単な方法は何ですか?自分なりに調べてみたのですが、わかりません。リスト a とリスト b の場合、新しいリストにはリスト a のみにある項目が含まれている必要があります。そう:

a = apple, carrot, lemon
b = pineapple, apple, tomato
new_list = carrot, lemon

コードを書いてみましたが、常にリスト全体が返されます。

4

5 に答える 5

54

これはリスト内包表記を使って書くことができます。リスト内包表記は、どの要素が で終わる必要があるかを文字通り教えてくれますnew_list

a = ['apple', 'carrot', 'lemon']
b = ['pineapple', 'apple', 'tomato']

# This gives us: new_list = ['carrot' , 'lemon']
new_list = [fruit for fruit in a if fruit not in b]

または、for ループを使用します。

new_list = []
for fruit in a:
    if fruit not in b:
        new_list.append(fruit)

ご覧のとおり、これらのアプローチは非常に似ているため、Python にはリストを簡単に作成するためのリスト内包表記もあります。

于 2012-07-11T14:18:54.623 に答える
27

セットを使用できます:

# Assume a, b are Python lists

# Create sets of a,b
setA = set(a)
setB = set(b)

# Get new set with elements that are only in a but not in b
onlyInA = setA.difference(b)

更新
iurisilvio と mgilson が指摘したように、このアプローチは、重複を含まず、要素の順序が重要でない場合aにのみ機能します。b

于 2012-07-11T14:22:08.693 に答える
9

あなたはこれが欲しいかもしれません:

a = ["apple", "carrot", "lemon"]
b = ["pineapple", "apple", "tomato"]

new_list = [x for x in a if (x not in b)]

print new_list
于 2012-07-11T14:21:58.723 に答える
7

これはあなたのために働きますか?

a = ["apple", "carrot", "lemon"]
b = ["pineapple", "apple", "tomato"]

new_list = []
for v in a:
    if v not in b:
        new_list.append(v)

print new_list

または、より簡潔に:

new_list = filter(lambda v: v not in b, a)
于 2012-07-11T14:17:14.387 に答える
2

セットset(またはセットが 2.6 で非推奨になったので組み込み)を使用するのはどうですか?

from sets import Set
a = Set(['apple', 'carrot', 'lemon'])
b = Set(['pineapple','apple','tomato'])
new_set =  a.difference(b)
print new_set

出力を与える

Set(['carrot', 'lemon'])
于 2012-07-11T14:23:28.000 に答える