Sorting a list of lists in Python

前端 未结 3 1882
既然无缘
既然无缘 2020-12-16 02:39
c2=[]
row1=[1,22,53]
row2=[14,25,46]
row3=[7,8,9]

c2.append(row2)
c2.append(row1)
c2.append(row3)

c2 is now:

[[14, 25         


        
相关标签:
3条回答
  • 2020-12-16 03:13

    Well, your desired example seems to indicate that you want to sort by the last index in the list, which could be done with this:

    sorted_c2 = sorted(c2, lambda l1, l2: l1[-1] - l2[-1])
    
    0 讨论(0)
  • 2020-12-16 03:19
    >>> import operator
    >>> c2 = [[14, 25, 46], [1, 22, 53], [7, 8, 9]]
    >>> c2.sort(key=itemgetter(2))
    >>> c2
    [[7, 8, 9], [14, 25, 46], [1, 22, 53]]
    
    0 讨论(0)
  • 2020-12-16 03:27

    The key argument to sort specifies a function of one argument that is used to extract a comparison key from each list element. So we can create a simple lambda that returns the last element from each row to be used in the sort:

    c2.sort(key = lambda row: row[2])
    

    A lambda is a simple anonymous function. It's handy when you want to create a simple single use function like this. The equivalent code not using a lambda would be:

    def sort_key(row):
        return row[2]
    
    c2.sort(key = sort_key)
    

    If you want to sort on more entries, just make the key function return a tuple containing the values you wish to sort on in order of importance. For example:

    c2.sort(key = lambda row: (row[2],row[1]))
    

    or:

    c2.sort(key = lambda row: (row[2],row[1],row[0]))
    
    0 讨论(0)
提交回复
热议问题