python - python 中将此列表更改为另一个列表的功能方法

标签 python python-3.x algorithm functional-programming

<分区>

我有一个列表[2,3,0,3] 并想生成一个列表

[1,0,1,2]

推理是在输入列表中出现了1个零,没有出现1,出现了1个二,出现了2个三。

在 python 中是否有非 for 循环程序方法来执行此操作?

最佳答案

您可以使用 collections.Counter找到元素的数量:

from collections import Counter

lst = [2,3,0,3]

c = Counter(lst)
print([c[x] for x in range(max(lst)+1)])
# [1, 0, 1, 2]

另一种避免循环的方法:

from collections import Counter

lst = [2,3,0,3]

c = dict.fromkeys(range(max(lst)+1), 0)
c.update(Counter(lst))

print(c.values())
# # [1, 0, 1, 2]

关于python - python 中将此列表更改为另一个列表的功能方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54966155/

相关文章:

python - OrderedDict 的行为

python - 在 Windows 上升级 TensorFlow

algorithm - 寻找最少的变换次数

algorithm - 存储错误-第一次深度搜索算法

python - 用 f(x) 非破坏性地替换矩阵的列 x 的 numpy/pythonic 方法是什么?

python - 如何在 python 中处理意外的参数类型

python-3.x - 如何翻转二进制表示中的位模式?

python - Seaborn 热图 : Customize A Label

python - 从服务器流式传输视频

java - 文本文件中的通用二叉树