Reputation: 353
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.
Upvotes: 0
Views: 110
Reputation: 39443
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']
Upvotes: 0
Reputation: 1125058
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
Upvotes: 0
Reputation: 106
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()))
Upvotes: 1