简体   繁体   中英

What is a way to return a list of most common item in a list of lists?

If I had a list such as

[['dog','cat'],['bird','cat'],['dog','squirrel']]

, I am trying to find a way that I would return the most common elements at index [0] of the list among all the sublists and return this as a list.

So if I applied it to the list on top, it'd return:

 ['dog','bird'] 

as only those two were at position 0 for their lists and dog was more common.

Like this? You can specify how many you want in most_common.

import collections

animals = [['dog','cat'],['bird','cat'],['dog','squirrel']]
print(list(x[0] for x in collections.Counter(x[0] for x in animals).most_common()))

Use collections.Counter() to count strings and use the Counter.most_common() method to get the most-frequent item:

from collections import Counter

counts = Counter(item[0] for item in yourlist)
print counts.most_common(1)[0][0]

Demo:

>>> from collections import Counter
>>> yourlist = [['dog','cat'],['bird','cat'],['dog','squirrel']]
>>> counts = Counter(item[0] for item in yourlist)
>>> print counts.most_common(1)[0][0]
dog

Is that you mean to have the unique and common elements from the list index 0??

lst = [['dog','cat'],['bird','cat'],['dog','squirrel']];
new_lst = list(set([x[0] for x in lst]))
print new_lst

Output:

['dog', 'bird']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM