1

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

Chris Wesseling
  • 6,226
  • 2
  • 36
  • 72
user3591815
  • 25
  • 2
  • 6

3 Answers3

0

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.

taesu
  • 4,482
  • 4
  • 23
  • 41
0

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]
Community
  • 1
  • 1
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
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]
perreal
  • 94,503
  • 21
  • 155
  • 181