By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,621 Members | 1,077 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,621 IT Pros & Developers. It's quick & easy.

Is there any way that i can sort a List like this?

P: 7
Expand|Select|Wrap|Line Numbers
  1. List =[("Rail",2),("Airport",6),("Interstate",1),("jack",5),("Port",3),("intermodal",4),("MinPopulation",8),("Etc",7)]
i want to sort it like:
Expand|Select|Wrap|Line Numbers
  1.                   "Interstate",1
  2.                         "Rail",2
  3.                         "Port",3
  4.                         "intermodal",4
  5.                         "jack",5
  6.                         "Airport",6
  7.                         "Etc",7
  8.                         "MinPopulation",8
I TRIED USING SORTED()BUT WAS NOT ABLE TO OBTAIN DESIRED RESULT:

Expand|Select|Wrap|Line Numbers
  1.         sorted(List,key=operator.itemgetter(1))
cAN SOMEONE HELP ME WITH A BETTER SOLUTION?
Feb 8 '11 #1
Share this Question
Share on Google+
1 Reply


bvdet
Expert Mod 2.5K+
P: 2,851
This is a solution for Python 2.3:
Expand|Select|Wrap|Line Numbers
  1. >>> List =[("Rail",2),("Airport",6),("Interstate",1),("jack",5),("Port",3),("intermodal",4),("MinPopulation",8),("Etc",7)]
  2. >>> List.sort(lambda a,b: cmp(a[1], b[1]))
  3. >>> List
  4. [('Interstate', 1), ('Rail', 2), ('Port', 3), ('intermodal', 4), ('jack', 5), ('Airport', 6), ('Etc', 7), ('MinPopulation', 8)]
  5. >>> 
Feb 8 '11 #2

Post your reply

Sign in to post your reply or Sign up for a free account.