我有列表名单,名字和名字。
如何获得大于3的姓氏数。
import collections
names = [['Fiona','Murray'],
['Diane','Springer'],
['Dylan','Oliver'],
['Alison','McDonald'],
['Sophie','Peters'],
['Kevin','Davidson'],
['David','Marshall'],
['Jake','Lewis'],
['Thomas','Burgess'],
['Fiona','Murray'],
['Fiona','Murray'],
['Fiona','Murray'],
['Fiona','Murray'],
['Dylan','Oliver'],
['Dylan','Oliver'] ]
lst1 = [(a,b) for (a,b) in collections.Counter(map(tuple,names)).iteritems()]
我尝试了列表理解,但无法获得大于3的姓氏。
答案 0 :(得分:3)
您可以使用collections.Counter
:
from collections import Counter
counter = Counter([item[1] for item in names])
keys = [key for key, value in counter.items() if value > 3]
print(keys)
将打印:
['Murray']
答案 1 :(得分:2)
更具功能性的编程方法。
from collections import Counter
from operator import itemgetter
from itertools import imap
[(name, count) for name, count in Counter(imap(itemgetter(1), names)).iteritems() if count > 3]
答案 2 :(得分:1)
首先,您在collections.Counter
中使用完整的元组(名字和姓氏),根据需要,您只需要使用每个内部列表的第二个元素(不是完整的)内部列表转换为元组。)
其次,在列表理解中,没有条件检查计数是否大于3.您应该检查b
是否大于3。
示例 -
>>> lst1 = [(a,b) for (a,b) in collections.Counter([a[1] for a in names]).iteritems() if b > 3]
>>> lst1
[('Murray', 5)]
答案 3 :(得分:1)
lst1=[entry[0] for entry in collections.Counter(map(tuple,names)).iteritems() if entry[1]>3]
并且对于计数,只需将len()放在它前面。