+ 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)

27th Aug 2019, 4:09 PM
Habeeba Fatima
Habeeba Fatima - avatar
4 odpowiedzi
+ 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 😅
27th Aug 2019, 4:43 PM
Burey
Burey - avatar
+ 5
Exactly something like that Diego 😅
27th Aug 2019, 7:15 PM
Burey
Burey - avatar
+ 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]]))
27th Aug 2019, 6:10 PM
Diego
Diego - avatar
+ 2
Thanks
27th Aug 2019, 4:49 PM
Habeeba Fatima
Habeeba Fatima - avatar