1
我想知道如何得到每個項目有多少個字符串。例如像:如何獲取每個項目在列表中的數量?
{"harley": ["apple", "apple", "banana"]}
那麼我將如何得到這個:
Harley has Apple x 2 and Banana x 1
我想知道如何得到每個項目有多少個字符串。例如像:如何獲取每個項目在列表中的數量?
{"harley": ["apple", "apple", "banana"]}
那麼我將如何得到這個:
Harley has Apple x 2 and Banana x 1
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())))
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())
看看['collections.Counter'(HTTP://docs.python。 org/2/library/collections.html#collections.Counter) – iCodez
列表也有一個'count'方法,但是如果你想統計所有的東西,效率就會低很多。 – user2357112
嗯。看起來像collections.Counter對此非常好。 – user3230748