You can use sets to get unique names present in the sub lists:
initial_list = [['banana', 'oranges', 'grapes'],['banana', 'grapes'],['grapes', 'oranges', 'banana']]
unique = set()
for l in initial_list:
unique = unique.union(set(l))
Then counting in how many list each item is present (assuming each item is either present or not, not duplicated):
from collections import defaultdict
result = defaultdict(lambda: 0)
for element in unique:
for l in initial_list:
result[element] += (element == l[0])
Defaultict is used to get an initial value of 0
And you should have your result in result
The fact thatbool
are a subclass of int
is used to evaluate element == l[0]
either to 1
or 0
Without collections
you would need to edit the last line to be:
try:
result[element] += (element == l[0])
except KeyError:
result[element] = 1