Count occurrence of a list in a List of Lists in Python -
i have list looks this:
co_list = [[387, 875, 125, 822], [397, 994, 135, 941], [397, 994, 135, 941], [397, 994, 135, 941], [397, 994, 135, 941], [1766, 696, 1504, 643]. . . ]
i need count number of identical co-ordinates lists , return count, 4 in case.
so far have tried:
def most_common(lst): lst = list(lst) return max(set(lst), key=lst.count) each in kk : print most_common(each)
using occurring element in each list. intention list if it's occurrence more 3.
expected output:
(element, count) = ([397, 994, 135, 941], 4)
any appreciated. thanks.
you can use collections.counter
task:
from collections import counter co_list = [[387, 875, 125, 822], [397, 994, 135, 941], [397, 994, 135, 941], [397, 994, 135, 941], [397, 994, 135, 941], [1766, 696, 1504, 643]] common_list, appearances = counter([tuple(x) x in co_list]).most_common(1)[0] # note 1 if appearances > 3: print((list(common_list), appearances)) # ([397, 994, 135, 941], 4) else: print('no list appears more 3 times!')
1) inner list
s converted tuple
s because counter
builds dict
, list
s being not hashable cannot used key
s.
Comments
Post a Comment