Home > Back-end >  How to get the more repeated combination of list elements from a python list
How to get the more repeated combination of list elements from a python list

Time:08-20

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.

CodePudding user response:

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')
  • Related