搜索列表并与另一个不精确的列表比较
我有两个列表,它们并不是完全相同,但里面的内容有很多相似的地方。我想把这两个列表进行比较,找出哪些内容是匹配的,哪些是不匹配的,最后得到一个结果列表。
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
3 个回答
0
对于你提供的数据,我会这样做:
set([el[el.find('[')+1:-1] for el in compare]).intersection(name)
输出结果是:
set(['bark', 'dentla', 'group'])
2
for n in name:
match = any(('[%s]'%n) in e for e in compare)
print "%10s %s" % (n, "YES" if match else "NO")
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
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