Advertisement
here2share

# sort_by_many_attributes_via_lambda_demo.py

Sep 8th, 2015
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.05 KB | None | 0 0
  1. # sort_by_many_attributes_via_lambda_demo.py
  2.  
  3. sss = [
  4.     ('tmp', 'bmp', 1000, 1200, 1200),
  5.     ('xyz', 'jpg', 600, 1200, 720),
  6.     ('123', 'jpg', 600, 1000, 600),
  7.     ('foo', 'jpg', 800, 1000, 800),
  8.     ('25', 'jpg', 800, 800, 640),
  9.     ('bar', 'gif', 1000, 800, 800),
  10.     ('abc', 'jpg', 600, 800, 480),
  11.     ('456', 'gif', 800, 1200, 960),
  12.     ('s25', 'gif', 1000, 1000, 1000)]
  13.  
  14. options = '1:Filename 2:Type 3:Width 4:Height 5:Size'.split()
  15.  
  16. def keyattr():
  17.     for s in sss: print '\t\t\t%s\t%s\t%s\t%s\t%s'%(s)
  18.     return raw_input("\nSort List By... \
  19.     \n"+' '.join(options)+" (Q:To Exit) \
  20.     \nAnd Re-Enter Attribute # To Reverse The Order. \
  21.     \nKey Selection ::: ")
  22.  
  23. choice = keyattr()
  24. while choice.lower() != 'q':
  25.     if choice in '12345':
  26.         i = int(choice)-1
  27.         tmp=sss
  28.         sss=sorted(sss,key=lambda x: x[i]) # <<<<<
  29.         for s in range(len(sss)):
  30.             if sss[s][i] != tmp[s][i]: tmp=1; break
  31.         if tmp != 1: sss=sss[::-1] # sss=reversed(sss, reverse=True) as also sss=reversed(sss) does not work properly
  32.         print;print
  33.         print 'Option -- '+options[i]+'\n'
  34.     choice = keyattr()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement