<分区>
我有一个列表[2,3,0,3]
并想生成一个列表
[1,0,1,2]
推理是在输入列表中出现了1个零,没有出现1,出现了1个二,出现了2个三。
在 python 中是否有非 for
循环程序方法来执行此操作?
<分区>
我有一个列表[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/