Searching lists and comparing with another not exact list
I have two lists that are not exact matches but do not content that almost match and I want to compare them and get out a list of one that match and do not match:
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
You can use comprehensions for making compare list usable; and you can check items in name with 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}
If you want to print it:
>>> 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
Edit:
Or if you want just to print them, you can do it easily with a for loop:
>>> 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")
For your given data, I'd do it like this:
set([el[el.find('[')+1:-1] for el in compare]).intersection(name)
The output is:
set(['bark', 'dentla', 'group'])
精彩评论