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

时间:2013-10-19 04:59:12

标签: python

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 loop ,通过索引来查看数字和修改频率的元素。 频率应如下所示:

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

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

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:2)

假设数字的每个元素都在0和频率之间,包括 - 独占:

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

答案 2 :(得分:0)

计数器对此很有用。

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