operator.itemgetter() syntax

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rogerlew
    New Member
    • Jun 2007
    • 15

    operator.itemgetter() syntax

    Hi all,

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

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

    Thank you for your help.
  • rogerlew
    New Member
    • Jun 2007
    • 15

    #2
    I figured it out.
    Code:
    for key in sorted(M_keys,key=operator.itemgetter(*keyindices)):

    Comment

    • ilikepython
      Recognized Expert Contributor
      • Feb 2007
      • 844

      #3
      Originally posted by rogerlew
      I figured it out.
      Code:
      for key in sorted(M_keys,key=operator.itemgetter(*keyindices)):
      Glad you fixed your problem. :)

      Comment

      • rogerlew
        New Member
        • Jun 2007
        • 15

        #4
        The method described above works for Python 2.5 but not for 2.4.4. Operator.itemge tter 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.

        [CODE=python]
        def SortKeyByIndice s(keylist,indic es):
        sortedkeys=sort ed(keylist,key= operator.itemge tter(indices[0]))
        if len(indices)>1:
        teeth=[]
        teeth.append([sortedkeys[0][indices[0]],0])
        for ikey, key in enumerate(sorte dkeys):
        if key[indices[0]]!=teeth[-1][0]:
        teeth.append([key[indices[0]],ikey])
        teeth.append([teeth[-1][0],len(sortedkeys )])
        for tnum, tooth in enumerate(teeth[:-1]):
        subkeys=sortedk eys[teeth[tnum][1]:teeth[tnum+1][1]]
        subkeys=SortKey ByIndices(subke ys,indices[1:])
        sortedkeys[teeth[tnum][1]:teeth[tnum+1][1]]=subkeys
        return sortedkeys
        [/CODE]

        Usage
        [CODE=python]
        mykeys=mylist.k eys()
        mykeyssorted=So rtKeyByIndices( mykeys,[1,2,5,6])
        [/CODE]

        Comment

        Working...