0

I have an array of numbers and want to print out how many of each number there are in the array. My method works but I was wondering what a more efficient way of doing this would be. I figure a loop would work but I haven't figured out how to do it with this:

s='1234444432187667890000568984'
print 'I found %i:' % s.count('0'),0
print 'I found %i:' % s.count('1'),1
print 'I found %i:' % s.count('2'),2
print 'I found %i:' % s.count('3'),3
print 'I found %i:' % s.count('4'),4
print 'I found %i:' % s.count('5'),5
print 'I found %i:' % s.count('6'),6
print 'I found %i:' % s.count('7'),7
print 'I found %i:' % s.count('8'),8
print 'I found %i:' % s.count('9'),9

I did find this snippet which is fast in counting but doesn't print out like I want it to:

s='1234444432187667890000568984'
ans=dict((i,s.count(i)) for i in set(s))
print ans
2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by kiddo39
1
s='1234444432187667890000568984'
print("\n".join(("I found %d: %d" % (s.count(str(i)), i)) for i in range(10)))
Votes + Comments
Thanks!
0

Wow :) very impressive and exactly what I was looking for. Thanks!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.