I wondered how to create an array of 10 digits, such that each time a digit of a number shows, it increments its matching place in the 10 digits array, like this:
digits=[0,0,0,0,0,0,0,0,0,0]
num_digits=[1,2,3,9,1]
and digits becomes:
digits=[0,2,1,1,0,0,0,0,0,1]
I tried:
digits[num_digits[j]]=digits[num_digits[j]]+1
(j goes backwards on num_digits elements) but I got the error "list indices must be integers, not list".
Thanks in advance!
>>> digits=[0,0,0,0,0,0,0,0,0,0]
>>> num_digits=[1,2,3,9,1]
>>> for d in num_digits:
... digits[d] += 1
...
>>> digits
[0, 2, 1, 1, 0, 0, 0, 0, 0, 1]
We wouldn't need a variable j
for a simple iteration of a list.
It might be worth using a dict
rather than a list
to store your totals. You could then use defaultdict
from collections
to create a dict
which will automatically create a entry with a zero int
for new keys:
>>> from collections import defaultdict
>>> digits = defaultdict(int)
>>> num_digits = [1,2,3,9,1]
>>> for d in num_digits:
... digits[d] += 1
...
>>> digits
defaultdict(<type 'int'>, {1: 2, 2: 1, 3: 1, 9: 1})
>>> digits[1]
2
>>> digits[8]
0
You can use collections.Counter
for that task as follows:
from collections import Counter
num_digits=[1,2,3,9,1]
digits = [0]*10
for key, value in Counter(num_digits).items():
digits[key] = value
在这里,您可以找到如何在python中实现计数排序: http : //en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Counting_sort#Python
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.