如何获取列表中每个项目的数量?

时间:2014-01-24 22:33:27

标签: python

我正在试图弄清楚如何获得字符串中每个项目的数量。例如:

{"harley": ["apple", "apple", "banana"]}

那我怎么能得到这个:

Harley has Apple x 2 and Banana x 1

2 个答案:

答案 0 :(得分:2)

from collections import Counter

d = {"harley": ["apple", "apple", "banana"]}
for k,v in d.items():
    print("%s has %s" %(k, ', '.join("%s x %s"%(k,v) for k,v in Counter(v).items())))

答案 1 :(得分:2)

d = {"harley": ["apple", "apple", "banana"]}

from collections import Counter
for k,v in d.iteritems():
    print k + ' has ' + ' and '.join('{0} x {1}'.format(name, count) for name, count in Counter(v).iteritems())