[英]How to count list elements within list on python
I sorted lists within list on python. 我在python列表中对列表进行了排序。 but I need to count list elements too. 但我也需要计算列表元素。 following list: 以下列表:
fruit = [
['Apple', 'S+'], ['Apple', 'S+'], ['Apple', 'B+'],
['Grape', 'B+'], ['Grape', 'C+']
]
result: 结果:
{'Apple':{'total':3, 'S+':2, 'B+':1}, 'Grape':{'total':2, 'B+':1, 'C+':1}}
I got above result through several for and while. 我通过几次和一段时间都超过了结果。 but I want simple way. 但我想要简单的方法。 Is there beautiful and simple way to get result above thing ? 有没有一种简单易行的方法来获得高于结果的结果?
itertools.groupby is fun. itertools.groupby很有趣。
>>> result = {}
>>> for k, v in groupby(fruit,lambda x:x[0]):
... value = list(v)
... result[k] = {'total':len(value)}
... for i,j in groupby(value, lambda x:x[1]):
... result[k].update({i:len(list(j))})
Output: 输出:
{'Grape': {'total': 2, 'C+': 1, 'B+': 1}, 'Apple': {'total': 3, 'S+': 2, 'B+': 1}}
NB NB
Though, not needed here, it is always wise to sort the collection before applying groupby. 尽管这里不需要,但是在应用groupby之前对集合进行排序总是明智的。 For this example: 对于此示例:
fruit = sorted(fruit, key= lambda x:(x[0],x[1]))
Something approaching what you want, using collections.defaultdict
and collections.Counter
. 使用collections.defaultdict
和collections.Counter
可以满足您的需求。
I tried to make it as pythonic as possible. 我试图使它尽可能pythonic。
import collections
fruit = [
['Apple', 'S+'], ['Apple', 'S+'], ['Apple', 'B+'],
['Grape', 'B+'], ['Grape', 'C+']
]
d = collections.defaultdict(lambda : [collections.Counter(),0])
for k,v in fruit:
d[k][0][v]+=1
d[k][1]+=1
print(dict(d)) # convert to dict for readability when printing
result: 结果:
{'Grape': [Counter({'B+': 1, 'C+': 1}), 2], 'Apple': [Counter({'S+': 2, 'B+': 1}), 3]}
details: 细节:
collections.Counter
object and an integer (for global count) 此元素列表由collections.Counter
对象和一个整数(用于全局计数)组成 unique, counts = numpy.unique(fruits, return_counts=True)
在numpy 1.9.0 return_counts
添加到唯一
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.