2024-06-16 12:24:31 发布
网友
将列表/元组转换为dict的最佳方法是什么?dict的键是列表的不同值,值是这些不同值的频率?
换句话说:
['a', 'b', 'b', 'a', 'b', 'c'] --> {'a': 2, 'b': 3, 'c': 1}
(我已经做了很多次像上面这样的事情,标准库中有没有什么东西能帮到你呢?)
编辑:
Jacob Gabrielson指出2.7/3.1分支有something coming in the standard lib
请注意,从Python 2.7/3.1开始,此功能将内置到collections模块中,有关更多信息,请参见this bug。下面是来自release notes的示例:
collections
>>> from collections import Counter >>> c=Counter() >>> for letter in 'here is a sample of english text': ... c[letter] += 1 ... >>> c Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2, 'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1, 'p': 1, 'r': 1, 'x': 1}) >>> c['e'] 5 >>> c['z'] 0
我发现最容易理解(虽然可能不是最有效的)的方法是:
{i:words.count(i) for i in set(words)}
有点
from collections import defaultdict fq= defaultdict( int ) for w in words: fq[w] += 1
通常效果很好。
请注意,从Python 2.7/3.1开始,此功能将内置到
collections
模块中,有关更多信息,请参见this bug。下面是来自release notes的示例:我发现最容易理解(虽然可能不是最有效的)的方法是:
有点
通常效果很好。
相关问题 更多 >
编程相关推荐