重複の可能性:
Python で 2 つのリストから違いを取得する
これを行う簡単な方法は何ですか?自分なりに調べてみたのですが、わかりません。リスト a とリスト b の場合、新しいリストにはリスト a のみにある項目が含まれている必要があります。そう:
a = apple, carrot, lemon
b = pineapple, apple, tomato
new_list = carrot, lemon
コードを書いてみましたが、常にリスト全体が返されます。
重複の可能性:
Python で 2 つのリストから違いを取得する
これを行う簡単な方法は何ですか?自分なりに調べてみたのですが、わかりません。リスト a とリスト b の場合、新しいリストにはリスト a のみにある項目が含まれている必要があります。そう:
a = apple, carrot, lemon
b = pineapple, apple, tomato
new_list = carrot, lemon
コードを書いてみましたが、常にリスト全体が返されます。
これはリスト内包表記を使って書くことができます。リスト内包表記は、どの要素が で終わる必要があるかを文字通り教えてくれます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 にはリストを簡単に作成するためのリスト内包表記もあります。
セットを使用できます:
# 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
あなたはこれが欲しいかもしれません:
a = ["apple", "carrot", "lemon"]
b = ["pineapple", "apple", "tomato"]
new_list = [x for x in a if (x not in b)]
print new_list
これはあなたのために働きますか?
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)