2

I have a list that looks something like 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 to count the number of identical co-ordinates lists and return the count, 4 in this case.

So far I have tried:

def most_common(lst):
    lst = list(lst)
    return max(set(lst), key=lst.count)

for each in kk :
    print most_common(each) 

Using which I get the most occurring element in each list. But my intention is to get a list if it's occurrence is more than 3.

Expected Output:

(element, count) = ([397, 994, 135, 941], 4) 

Any help would be appreciated. Thanks.

coder3521
  • 2,608
  • 1
  • 28
  • 50
  • Possible duplicate of [How can I count the occurrences of a list item in Python?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python) – Mohd Aug 18 '17 at 13:48
  • @MoeA : I am glad that you are working great to remove duplicates , but this is different from what is asked in the link you posted , – coder3521 Aug 21 '17 at 07:57

2 Answers2

4

You can use collections.Counter for that 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) for 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 than 3 times!')

1) The inner lists are converted to tuples because Counter builds a dict and lists being not hashable cannot be used as keys.

Ma0
  • 15,057
  • 4
  • 35
  • 65
0
from collections import Counter

def get_most_common_x_list(origin_list, x):

    counter = Counter(tuple(item) for item in origin_list)

    for item, count in most_common_list = counter.most_common():

        if count > x:

            yield list(item), count

        else:

            break
stamaimer
  • 6,227
  • 5
  • 34
  • 55