How to get the more repeated combination of list elements from a python list

Question:

I have few lists of names as below;

[['mallesham','yamulla'],['mallesham','yamulla'],['yamulla','mallesham']]

Here mallesham yamulla and mallesham yamulla person name is counted as two times hence the output should be [‘mallesham’,’yamulla’]

Second example:

[['Joe','Doe'],['Doe','Joe'],['Doe','Joe'],['Joe','Doe'],['Doe','Joe']]

Here Doe Joe counted as 3 times where as Joe Doe as 2 times, hence the output will be [‘Doe’,’Joe’]

In a 3rd case: what if all names have got equal number of counts as below

[['Joe','Doe'],['Doe','Joe'],['Doe','Joe'],['Joe','Doe']]

It should return any one of name such as Joe Doe.

Asked By: myamulla_ciencia

||

Answers:

You can use:

from collections import Counter
l = [['Joe','Doe'],['Doe','Joe'],['Doe','Joe'],['Joe','Doe'],['Doe','Joe']]
c = Counter([tuple(x) for x in l]).most_common(1)[0][0]
c
# ('Doe', 'Joe')
Answered By: Jonas Palačionis
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.