Search code examples
pythonspss

Cannot sort list of items with float using lambda. What do?


I have a list of items containing a list of lists, like:


lst=
['0038b49c491bb67c9459318c2afce65f        ', 13653705600.0, 13657075200.0]
['0038bad168c0358a65f56ce04ebb0bfa        ', 13724726400.0, 13728441600.0]
['0038e2c5f01fedfa0b4025699374c2a4        ', 13709952000.0, 13723948800.0]
['0038e75eee2104045dfe323a3097e7af        ', 13468204800.0, 13471142400.0]
['0038eb7855072fd017250641fe8ab98b        ', 13700448000.0, 13700448000.0]
['0038eb982de28f0372dbb5c9a76b8db0        ', 13526784000.0, 13526784000.0]
['0038edbe1afe7308d21eb3657952b6e7        ', 13475548800.0, 13476758400.0]

i'm trying to create a copy of this list which sorts by the first item, then the second item.

I've been doing research and have tried: lst2=sorted(lst, key=lambda x: x[1])

To which i get this error:

TypeError: 'float' object is not subscriptable

I've also tried itemgetter, which gets me the same error.

Here's the code - it's intended to be an SPSS function which creates a variable based upon a hierarchy of dates.

def rcnv():
    
        index=spssaux.VariableDict().VariableIndex
        v_idx=[index(v) for v in varlist]
        
        vals = [None] * len(v_idx)
        row_to_all=[]
        for i,v in enumerate(v_idx):
            row_to_all.append(i)
        
        cur=spss.Cursor(var=v_idx, accessType='w')
        #cvtDates="ALL"
        for i in range(cur.GetCaseCount()):
            row=cur.fetchone()
            for i,v in enumerate(row):
                j=row_to_all[i]
                vals[j]=v
            
              
            (CaseID, Dispo,Prosecuted, Cnvctd, Violent, Dt1, Dt2, Dt3, Dt4) = vals
    
            lst=[]
            lst.append(CaseID)

            
            if Prosecuted== 1 and CaseDisposition== 2:  
                repeat(lst, Dt1, Dt2, Dt3,Dt)
            elif Prosecuted== 1:  
                repeat(lst, Dt1, Dt2, Dt3,Dt4)
            elif Prosecuted== 0:  
                repeat(lst, Dt1, Dt2, Dt3,Dt4)
            else:  
                repeat(lst, Dt1, Dt2, Dt3,Dt4)
                  
            print(lst)
            lst2=sorted(lst, key=lambda x: x[1])
            
                          
rcnv()

Solution

  • You can actually just use this:

    my_list = sorted(lst)
    

    Sorted will use the order to sort (it will first try to sort on item 1 of each list, then om item 2).

    A working example:

    lst =[["a", 2], ["a", 1], ["c", 1], ["b",2]]
    # expect this to be sorted in (index) order 1,0,3,2
    print(sorted(lst))
    # > [['a', 1], ['a', 2], ['b', 2], ['c', 1]]
    #        1         0         3         2