Sorting a Python list by two fields

前端 未结 7 1029
不思量自难忘°
不思量自难忘° 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:27

    In ascending order you can use:

    sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]))
    

    or in descending order you can use:

    sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]),reverse=True)
    
    0 讨论(0)
  • 2020-11-22 08:30

    like this:

    import operator
    list1 = sorted(csv1, key=operator.itemgetter(1, 2))
    
    0 讨论(0)
  • 2020-11-22 08:36
    list1 = sorted(csv1, key=lambda x: (x[1], x[2]) )
    
    0 讨论(0)
  • 2020-11-22 08:47

    Sorting list of dicts using below will sort list in descending order on first column as salary and second column as age

    d=[{'salary':123,'age':23},{'salary':123,'age':25}]
    d=sorted(d, key=lambda i: (i['salary'], i['age']),reverse=True)
    

    Output: [{'salary': 123, 'age': 25}, {'salary': 123, 'age': 23}]

    0 讨论(0)
  • 2020-11-22 08:48

    No need to import anything when using lambda functions.
    The following sorts list by the first element, then by the second element.

    sorted(list, key=lambda x: (x[0], -x[1]))
    
    0 讨论(0)
  • 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]))

    0 讨论(0)
提交回复
热议问题