Python 查找列表中出现的数字
我想要比较一个包含数字序列的列表和一个python字典,以便找到数字的出现。 程序的行为:Python 查找列表中出现的数字,python,python-3.x,Python,Python 3.x,我想要比较一个包含数字序列的列表和一个python字典,以便找到数字的出现。 程序的行为: 函数occurences(L)以列表作为参数 函数occurences(L)返回一个字典,其键是列表中的元素,值是元素出现的次数 结果示例: >>> occurrences([1,3,2,1,4,1,2,1]) # input {1:4,2:2,3:1,4:1} # output 如果您想要一种更简单/更具python风格的方法来实现这一点,我建议您查看collections库中的
- 函数occurences(L)以列表作为参数
- 函数occurences(L)返回一个字典,其键是列表中的元素,值是元素出现的次数
>>> occurrences([1,3,2,1,4,1,2,1]) # input
{1:4,2:2,3:1,4:1} # output
如果您想要一种更简单/更具python风格的方法来实现这一点,我建议您查看
collections
库中的子类。要达到预期效果,您需要做的就是:
from collections import Counter
liste = [1,3,2,1,4,1,2,1]
n_occurences = Counter(liste) # returns {1:4,2:2,3:1,4:1}, which is
# the same thing as your function occurences(liste)
而且。。。问题是什么?代码有问题吗?有什么不起作用吗?同样值得注意的是:
len(Counter(liste))
是列表中唯一值的数目,尽管您可以使用len(set(liste))
获得相同的信息。
from collections import Counter
liste = [1,3,2,1,4,1,2,1]
n_occurences = Counter(liste) # returns {1:4,2:2,3:1,4:1}, which is
# the same thing as your function occurences(liste)
{i:liste.count(i) for i in set(liste)}