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

operator.itemgetter() syntax

P: 15
Hi all,

I need to pass operator.itemgetter(item,...) multiple arguments but the number of arguments is variable.

Expand|Select|Wrap|Line Numbers
  1. ivlist=['var1','var2','var3'] # This variable changes length
  2. keyindices=range(-len(ivlist)-1,0) # = [-4, -3, -2, -1] in this example
  3.  
  4. # What I want in this example is
  5. M_keys=M.keys()
  6. for key in sorted(M_keys,key=operator.itemgetter(-4, -3, -2, -1)):
  7.     # for loop code
  8.  
What is the syntax for passing operator.itemgetter(items,...) the values of the keyindices list as separate arguments?

Thank you for your help.
Jun 6 '07 #1
Share this Question
Share on Google+
3 Replies


P: 15
I figured it out.
Expand|Select|Wrap|Line Numbers
  1. for key in sorted(M_keys,key=operator.itemgetter(*keyindices)):
  2.  
Jun 6 '07 #2

ilikepython
Expert 100+
P: 844
I figured it out.
Expand|Select|Wrap|Line Numbers
  1. for key in sorted(M_keys,key=operator.itemgetter(*keyindices)):
  2.  
Glad you fixed your problem. :)
Jun 6 '07 #3

P: 15
The method described above works for Python 2.5 but not for 2.4.4. Operator.itemgetter only accepts one argument under 2.4.4. Another problem I found was that with 2.5 the * will only flatten a sequence. So if you want to sort by unordered a set of unordered indices (e.g. -1, 4,5,6) your out of luck (from want I tried at least).

I ended writing a function which works with 2.4 and 2.5. I am posting it here encase someone runs into the same problem and happens to google this in the future.

Expand|Select|Wrap|Line Numbers
  1. def SortKeyByIndices(keylist,indices):
  2.     sortedkeys=sorted(keylist,key=operator.itemgetter(indices[0]))
  3.     if len(indices)>1:
  4.         teeth=[]
  5.         teeth.append([sortedkeys[0][indices[0]],0])
  6.         for ikey, key in enumerate(sortedkeys):
  7.             if key[indices[0]]!=teeth[-1][0]:
  8.                 teeth.append([key[indices[0]],ikey])
  9.         teeth.append([teeth[-1][0],len(sortedkeys)])
  10.         for tnum, tooth in enumerate(teeth[:-1]):
  11.             subkeys=sortedkeys[teeth[tnum][1]:teeth[tnum+1][1]]
  12.             subkeys=SortKeyByIndices(subkeys,indices[1:])
  13.             sortedkeys[teeth[tnum][1]:teeth[tnum+1][1]]=subkeys
  14.     return sortedkeys
  15.  
Usage
Expand|Select|Wrap|Line Numbers
  1. mykeys=mylist.keys()
  2. mykeyssorted=SortKeyByIndices(mykeys,[1,2,5,6])
  3.  
Jun 8 '07 #4

Post your reply

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