I have a list that contains multiple lists of tuples. I want to compare each tuple to every other tuple in the lists and return a count of the exact matches.
foo = [[('a',),('a','b'),('a','b','c'),('b','c'),('c',)],[('a',),('a','b')]]
Expected results:
('a',) 2
('a','b') 2
('a','b','c') 1
('b','c') 1
('c',) 1
Any help appreciated.
Using collections.Counter
:
>>> import itertools
>>> import collections
>>>
>>> foo = [[('a',),('a','b'),('a','b','c'),('b','c'),('c',)],[('a',),('a','b')]]
>>> for x, cnt in collections.Counter(itertools.chain.from_iterable(foo)).most_common():
... print(x, cnt)
...
('a',) 2
('a', 'b') 2
('a', 'b', 'c') 1
('c',) 1
('b', 'c') 1
You need to merge all the lists into one, and then you can use Collections.Counter
, like this
foo = [[('a',),('a','b'),('a','b','c'),('b','c'),('c',)],[('a',),('a','b')]]
from collections import Counter
print Counter(item for items in foo for item in items)
Output
Counter({('a', 'b'): 2, ('a',): 2, ('b', 'c'): 1, ('c',): 1, ('a', 'b', 'c'): 1})
The same result can be achieved with normal dict
as well
result = {}
for items in foo:
for item in items:
result[item] = result.get(item, 0) + 1
print result
Output
{('b', 'c'): 1, ('c',): 1, ('a', 'b'): 2, ('a',): 2, ('a', 'b', 'c'): 1}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.