python - Python 中的一行频率字典

标签 python

给定一个可迭代对象(如字符串或列表或其他东西),是否有一种干净的、O(n) 方法来制作一个字典,使用 1 行将元素映射到它们的频率?我不想使用任何外部库或模块

该代码应具有与以下代码段相同的功能:

s = 'abcaba'
freq = {}
for i in s:
  if i not in freq:
    freq[i] = 1
  else:
    freq[i] += 1

### and now, freq = {'a':3, 'b':2, 'c':1}

这是O(n),但只有几行。我也可以这样做:

s = 'abcaba'
freq = {i: s.count(i) for i in s}

### same thing, now freq = {'a':3, 'b':2, 'c':1}

这是 1 行,但它是 O(n2),因为 countO(n )并且你还有一个循环。

可能有一个我没有想到的简单解决方案。如果这是重复的,我深表歉意。

最佳答案

In [212]: s = 'abcaba'                                                                                                                                                                                                                                                        

In [213]: collections.Counter(s)
Out[213]: Counter({'a': 3, 'b': 2, 'c': 1})

这是另一种方法(尽管不完全是一句简单的话):

In [214]: freq = {}

In [215]: for char in s: freq[char] = freq.get(char, 0)+1

In [216]: freq
Out[216]: {'a': 3, 'b': 2, 'c': 1}

关于python - Python 中的一行频率字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66018272/

相关文章:

python - 存储远程 linux 服务器的加密密码存储

python - 使用 Python 基于不同列表构建矩阵

python - 改进 Python NetworkX 图形布局

python - pandas(水平)堆叠条形,每个条形段排序

python - conda环境从windows到linux

python - SA 警告 : Usage of the 'Session.add()' operation is not currently supported within the execution stage

python - 如何通过 Django 中的 AJAX 请求传递数据?

Python 多处理错误 : AttributeError: Can't get attribute 'task' on <module '__main__' (built-in)>"

python - py2exe 似乎缺少以下模块

python - Scrapy 蜘蛛爬行 0 页