简体   繁体   中英

How to get total occurrence of element in a list and create another list with this information:

Say I have a list of 5 string integers ['2', '2', '4','3'] and now I want to add the number of '2's to a list where the second element represents a count of how many '2's have occurred. How can I do this?

This is what I tried so far:

def rankbikelist(list):

list_only_rank = [] * 5
count = [] * 13
rank = '123456789'
for i in range(len(list)):
    list_only_rank += list[i][0]
    for j in range(12):
        count[j] = list_only_rank.count(rank[j])
return count

it gives me this error: list assignment index out of range

First you have a list of 4 string integers not 5.
I am not sure what you are trying to do.
Maybe reword the question a bit so I can try to help.

Your problem comes from the way you initialize your lists. [] * 13 really doesn't do anything. You meant [0] * 13 ; however, though it would work for this case, it's generally bad practice .

Try this:

In [5]: L = ['2', '2', '4','3']

In [6]: answer = [0 for _ in range(10)]

In [7]: for i in L:
   ...:     answer[int(i)] += 1
   ...:     

In [8]: answer
Out[8]: [0, 0, 2, 1, 1, 0, 0, 0, 0, 0]

You can use Counter to get the counts as a dictionary and convert that into a list:

from collections import Counter
items = ['2', '2', '4','3']
counts = Counter(items)
newlist = [ counts.get(str(x), 0) for x in range(10) ]
print newlist

Gives:

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

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