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.

2
  • Possible duplicate of How can I count the occurrences of a list item in Python? Commented Aug 18, 2017 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 , Commented Aug 21, 2017 at 7:57

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.