-4

I have an array of number which I changed to string

a="1423"
astr=str(a)
aspl=list(astr)

I should have ['1', '4', '2', '3']. I wanted to count how many 1~9 there are in the array so that 1 = 1 time(s), 2 = 1 time(s) ... 5 = 0 time(s), 6 = 0 time(s)...

My solution to this was

r=0
for r > 11:
    b = aspl.count(r)

but since it is a string, this method does not work. I tried using

    b = aspl.count('r')

then as you might have guessed, it's only looking for r. So how would you go about this?

Thanks in advance.

3 Answers3

5

the python collections module offers a Counter for just that:

from collections import Counter

a = '032143487214093120'

count = Counter(a)
print(count)
# Counter({'2': 3, '4': 3, '1': 3, '0': 3, '3': 3, '9': 1, '7': 1, '8': 1})

and then print with

for digit in (str(i) for i in range(10)):
    print('{}: {}x'.format(digit, count[digit]))

# 0: 3x
# 1: 3x
# ...
# 5: 0x
# ...

if you insist that also the digits that do not occur in your string appear in the counter, you can initialize the counter will all digits set to zero:

count = Counter({str(i): 0 for i in range(10)})
print(count)  # Counter({'2': 0, '4': 0, '9': 0, '0': 0, '8': 0, '3': 0,
              #          '1': 0, '7': 0, '5': 0, '6': 0})
count.update(a)
print(count)  # Counter({'2': 3, '4': 3, '0': 3, '3': 3, '1': 3, '9': 1, 
              #          '8': 1, '7': 1, '5': 0, '6': 0})
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
1
for i in range(10):
    print s.count(str(i))

I guess...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

Here's another possible solution which generates the results as a series of tuples:

s = '1423'
numbers = list(range(1, 10))
print(list((i, s.count(str(i))) for i in numbers))

Output

[(1, 1), (2, 1), (3, 1), (4, 1), (5, 0), (6, 0), (7, 0), (8, 0), (9, 0)]
Tagc
  • 8,736
  • 7
  • 61
  • 114