搜索列表并与另一个非精确列表进行比较

2024-09-30 16:35:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个不完全匹配的列表,但不满足于几乎匹配的内容,我要比较它们,然后列出一个匹配和不匹配的列表:

name = ['group', 'sound', 'bark', 'dentla', 'test']

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

^{pr2}$


Tags: nametest内容列表groupnotificationcomparefusion
3条回答

对于你给定的数据,我会这样做:

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

输出为:

^{pr2}$

您可以使用理解来使比较列表可用;还可以使用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}

如果要打印:

^{pr2}$

编辑:

或者,如果您只想打印它们,可以使用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
for n in name:
    match = any(('[%s]'%n) in e for e in compare)
    print "%10s %s" % (n, "YES" if match else "NO")

相关问题 更多 >