944,117 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Marked Solved
  • Views: 368
  • Python RSS
Oct 21st, 2009
0

more efficient print method

Expand Post »
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:

Python Syntax (Toggle Plain Text)
  1. s='1234444432187667890000568984'
  2. print 'I found %i:' % s.count('0'),0
  3. print 'I found %i:' % s.count('1'),1
  4. print 'I found %i:' % s.count('2'),2
  5. print 'I found %i:' % s.count('3'),3
  6. print 'I found %i:' % s.count('4'),4
  7. print 'I found %i:' % s.count('5'),5
  8. print 'I found %i:' % s.count('6'),6
  9. print 'I found %i:' % s.count('7'),7
  10. print 'I found %i:' % s.count('8'),8
  11. 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:

Python Syntax (Toggle Plain Text)
  1. s='1234444432187667890000568984'
  2. ans=dict((i,s.count(i)) for i in set(s))
  3. print ans
Similar Threads
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
kiddo39 is offline Offline
50 posts
since Nov 2008
Oct 21st, 2009
1
Re: more efficient print method
python Syntax (Toggle Plain Text)
  1. s='1234444432187667890000568984'
  2. print("\n".join(("I found %d: %d" % (s.count(str(i)), i)) for i in range(10)))
Reputation Points: 930
Solved Threads: 668
Posting Maven
Gribouillis is offline Offline
2,656 posts
since Jul 2008
Oct 21st, 2009
0
Re: more efficient print method
Wow very impressive and exactly what I was looking for. Thanks!
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
kiddo39 is offline Offline
50 posts
since Nov 2008

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: How to modify output result by using Python?
Next Thread in Python Forum Timeline: Panda or Pygame - just curious





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC