0

我不经常使用列表推导,但我想知道以下几行是否可以单行(是的,代码已经很小,但我很好奇):

lst = ['hi', 'hello', 'bob', 'hello', 'bob', 'hello']
for index in lst:
    data[index] = data.get(index,0) + 1

数据将是:{'hi':1, 'hello':3, 'bob':2}

某物:

d = { ... 用于 lst 中的索引 } ????

我尝试了一些理解,但它们不起作用:

d = { index:key for index in lst if index in d: key = key + 1 else key = 1 }

谢谢你的建议。

4

1 回答 1

3

只需使用collections.Counter

Counter 是用于计算可散列对象的 dict 子类。它是一个无序集合,其中元素存储为字典键,它们的计数存储为字典值。计数可以是任何整数值,包括零计数或负计数。Counter 类类似于其他语言中的 bag 或 multisets。

import collections
l = ['hi', 'hello', 'bob', 'hello', 'bob', 'hello']
c = collections.Counter(l)
assert c['hello'] == 3
于 2015-04-09T13:13:13.050 回答