简体   繁体   中英

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

Python 2.7.5 (Don't judge me)

What I have (eg):

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

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

I need a for loop that counts by going through the elements of numbers and modifying frequencies accordingly by indexing. frequencies should look like:

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

I tried using the len() function...for some reason...I just haven't found a way to incorporate count properly.

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

Assuming that every element of numbers is between 0 and the length of frequencies, inclusive-exclusive:

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

Counter works great for this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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