2011-06-27 8 views
0

完全一致ではないがほぼ一致する2つのリストがあり、それらを比較して一致するものと一致しないもののリストを取得したい:リストを検索して別の正確でないリストと比較する

あなたの与えられたデータについては
name = ['group', 'sound', 'bark', 'dentla', 'test'] 

compare = ['notification[bark]', 'notification[dentla]', 
      'notification[group]', 'notification[fusion]'] 

Name Compare 
Group YES 
Sound NO 
Bark YES 
Dentla YES 
test NO 
+1

"マッチ"と考えるものを定義する必要があります。 – interjay

+0

比較内容は本当に文字列ですか?または、比較リストのリストですか? – pajton

+0

毎日受け取って、受け取っていないものを知りたいと思っている宿題を読んでいません。 – namit

答えて

2

あなたが使用可能なリストを比較行うための内包表記を使用することができます。あなたはitem in clean_compareと名前の項目をチェックすることができます。

>>> clean_compare = [i[13:-1] for i in compare] 
>>> clean_compare 
['bark', 'dentla', 'group', 'fusion'] 
>>> name 
['group', 'sound', 'bark', 'dentla', 'test'] 
>>> {i:i in clean_compare for i in name} #for Python 2.7+ 
{'sound': False, 'dentla': True, 'bark': True, 'test': False, 'group': True} 

あなたはそれを印刷したい場合:

>>> d 
{'sound': False, 'dentla': True, 'bark': True, 'test': False, 'group': True} 
>>> for i,j in d.items(): 
...  print(i,j) 
... 
sound False 
dentla True 
bark True 
test False 
group True 

編集:

それとも、単にそれらを印刷したい場合は、あなたがそれを行うことができますがforループを使って簡単に:

>>> name 
['group', 'sound', 'bark', 'dentla', 'test'] 
>>> clean_compare 
['bark', 'dentla', 'group', 'fusion'] 
>>> for i in name: 
...  print(i, i in clean_compare) 
... 
group True 
sound False 
bark True 
dentla True 
test False 
2
for n in name: 
    match = any(('[%s]'%n) in e for e in compare) 
    print "%10s %s" % (n, "YES" if match else "NO") 
+0

これは探していたものに最適です。 – namit

0

、私はこのようにそれを行うだろう:

set([el[el.find('[')+1:-1] for el in compare]).intersection(name) 

出力は次のようになります。

set(['bark', 'dentla', 'group']) 
関連する問題