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
s='1234444432187667890000568984'
print("\n".join(("I found %d: %d" % (s.count(str(i)), i)) for i in range(10)))
commented: Thanks! +1

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.