如果我有一个列表,如
[['dog','cat'],['bird','cat'],['dog','squirrel']]
,我试图找到一种方法,在所有子列表中返回列表索引[0]中最常见的元素,并将其作为列表返回。
因此,如果我将它应用到顶部的列表中,它将返回:
['dog','bird']
因为只有那两个人在他们的名单上排在第0位并且狗更常见。
答案 0 :(得分:1)
喜欢这个?您可以在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()))
答案 1 :(得分:0)
使用collections.Counter()
计算字符串并使用Counter.most_common()
方法获取最常用的项目:
from collections import Counter
counts = Counter(item[0] for item in yourlist)
print counts.most_common(1)[0][0]
演示:
>>> 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
答案 2 :(得分:0)
你的意思是从列表索引0 ??
中获取unique and common
个元素
lst = [['dog','cat'],['bird','cat'],['dog','squirrel']];
new_lst = list(set([x[0] for x in lst]))
print new_lst
输出:
['dog', 'bird']