Sorting inventory list in Python

From , 5 Years ago, written in Python, viewed 212 times.
URL https://pastebin.vip/view/55acf853
  1. # sort an inventory list by item count
  2. # Python24 (needed)  modified by  vegaseat  10may2005
  3. import operator
  4. # create an inventory list of tuples
  5. # each tuple contains the item name and the count of the item
  6. inventory = [('apple', 35),('grape', 967),('banana', 12),('pear', 5),('cumquat', 10)]
  7. print '-'*50  # 50 dashes, cosmetic stuff
  8. print "Original inventory list:"
  9. print inventory
  10.  
  11. # establish the sort key
  12. # each tuple is zero based
  13. # item name = 0 and item count = 1
  14. getcount = operator.itemgetter(1)
  15. print "Inventory list sorted by item count:"
  16. # now sort by item count
  17. sortedInventory = sorted(inventory, key=getcount)
  18. print sortedInventory
  19. # more official look
  20. print "Fruit inventory:"
  21. for item in sortedInventory:
  22.     print "%-10s%6d" % (item[0], item[1])
  23. #//python/5739

Reply to "Sorting inventory list in Python"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website