more efficient print method

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: Nov 2008
Posts: 43
Reputation: kiddo39 is an unknown quantity at this point 
Solved Threads: 0
kiddo39 kiddo39 is offline Offline
Light Poster

more efficient print method

 
0
  #1
Oct 21st, 2009
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:

  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:

  1. s='1234444432187667890000568984'
  2. ans=dict((i,s.count(i)) for i in set(s))
  3. print ans
Reply With Quote Quick reply to this message  
Join Date: Jul 2008
Posts: 936
Reputation: Gribouillis is a jewel in the rough Gribouillis is a jewel in the rough Gribouillis is a jewel in the rough 
Solved Threads: 216
Gribouillis's Avatar
Gribouillis Gribouillis is offline Offline
Posting Shark
 
1
  #2
Oct 21st, 2009
  1. s='1234444432187667890000568984'
  2. print("\n".join(("I found %d: %d" % (s.count(str(i)), i)) for i in range(10)))
Reply With Quote Quick reply to this message  
Join Date: Nov 2008
Posts: 43
Reputation: kiddo39 is an unknown quantity at this point 
Solved Threads: 0
kiddo39 kiddo39 is offline Offline
Light Poster
 
0
  #3
Oct 21st, 2009
Wow very impressive and exactly what I was looking for. Thanks!
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC