![](/img/trans.png)
[英]Searching exact match of a list of strings inside a list of lists in Python
[英]Searching lists and comparing with another not exact list
我有兩個列表不完全匹配,但不滿足於幾乎匹配的內容,我想將它們進行比較,以得出一個匹配但不匹配的列表:
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
for n in name:
match = any(('[%s]'%n) in e for e in compare)
print "%10s %s" % (n, "YES" if match else "NO")
您可以使用理解使比較列表可用; 您可以使用item in clean_compare
檢查名稱中的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
對於您給定的數據,我會這樣做:
set([el[el.find('[')+1:-1] for el in compare]).intersection(name)
輸出為:
set(['bark', 'dentla', 'group'])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.