繁体   English   中英

如何获得一个列表中的数字频率,然后索引到另一个列表中?

[英]How do you get number frequencies in a list, then index into another list?

Python 2.7.5(不要判断我)

我所拥有的(例如):

numbers = [1,3,5,1,3,5,7,0,2,2,9,1]

frequencies = [0,0,0,0,0,0,0,0,0,0]

我需要一个for循环 ,该循环通过遍历数字元素并通过索引相应地修改频率来进行计数。 频率应如下所示:

[1,3,2,2,0,2,0,1,0,1]

我尝试使用len()函数...出于某种原因...我只是没有找到正确合并计数的方法。

for n in numbers:
    frequencies[n] += 1

假设数字的每个元素都在0到频率长度之间(包括非包括在内):

for i in range(len(frequencies)):
    frequencies[i] = numbers.count(i)

计数器对此非常有用。

from collections import Counter

numbers = [1,3,5,1,3,5,7,0,2,2,9,1]
freq = Counter(numbers)
# Counter({1: 3, 2: 2, 3: 2, 5: 2, 0: 1, 7: 1, 9: 1})

# dictionary
d = dict(freq)
#{0: 1, 1: 3, 2: 2, 3: 2, 5: 2, 7: 1, 9: 1}

# tuples
t = freq.items()
# [(0, 1), (1, 3), (2, 2), (3, 2), (5, 2), (7, 1), (9, 1)]

# list
L = [freq[n] for n in xrange(max(freq.keys()) + 1)]
# [1, 3, 2, 2, 0, 2, 0, 1, 0, 1]

# add more
freq.update(numbers)
# Counter({1: 6, 2: 4, 3: 4, 5: 4, 0: 2, 7: 2, 9: 2})  

collections.Counter

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM