+ 1
How do I count the common elements in different lists??
For example In List1 [1,2,3] In List2 [2,3] In List3 [1,3] By using what can I count the common elements of the list and get output 1:2 ( 1 is used 2 times) 2: 2 ( 2 is used 2 times) 3:3 ( 3 is used 3 times)
4 Respuestas
+ 8
def common(lists):
results = {}
for lst in lists:
for el in lst:
if el in results:
results[el] += 1
else:
results[el] = 1
return results
print(common([[1, 2, 3], [1, 2], [2, 3, 4]]))
you can also merge all the lists into one big list and just make one pass on it instead
there are probably some builtin tools in python that can do it better 😅
+ 5
Exactly something like that Diego 😅
+ 4
Burey
from collections import Counter
def common(lists):
return Counter([item for lst in lists for item in lst])
print(common([[1,2,3],[2,3],[1,3]]))
+ 2
Thanks