Sorting a Python list by two fields

前端 未结 7 1184
不思量自难忘°
不思量自难忘° 2020-11-22 07:51

I have the following list created from a sorted csv

list1 = sorted(csv1, key=operator.itemgetter(1))

I would actually like to sort the list

7条回答
  •  醉话见心
    2020-11-22 08:50

    employees.sort(key = lambda x:x[1])
    employees.sort(key = lambda x:x[0])
    

    We can also use .sort with lambda 2 times because python sort is in place and stable. This will first sort the list according to the second element, x[1]. Then, it will sort the first element, x[0] (highest priority).

    employees[0] = Employee's Name
    employees[1] = Employee's Salary
    

    This is equivalent to doing the following: employees.sort(key = lambda x:(x[0], x[1]))

提交回复
热议问题