我有两个不完全匹配的列表但是内容几乎不匹配,我想比较它们并找出一个匹配且不匹配的列表:
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
答案 0 :(得分:2)
for n in name:
match = any(('[%s]'%n) in e for e in compare)
print "%10s %s" % (n, "YES" if match else "NO")
答案 1 :(得分: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 :(得分:0)
对于您提供的数据,我这样做:
set([el[el.find('[')+1:-1] for el in compare]).intersection(name)
输出结果为:
set(['bark', 'dentla', 'group'])