基于元素以不同顺序对列表进行排序

时间:2021-02-12 06:44:34

标签: python-3.x

我有一个列表列表,想根据以下顺序对这些列表进行排序 date(7th index asc), datetime(6th index asc), type(4th index desc)

from operator import itemgetter

ll = [['2020-02-08', 1, 0, '1001', 'PS', 20, '2021-01-01 10:00:00', '2021-01-01'], 
      ['2020-02-08', 2, 0, '1002', 'VS', 30, '2021-01-01 11:00:00', '2021-01-01']]

sorted_list = sorted(ll, key=itemgetter(7, 6, 4))
print(sorted_list)

output:
[['2020-02-08', 1, 0, '1001', 'PS', 20, '2021-01-01 10:00:00', '2021-01-01'], 
['2020-02-08', 2, 0, '1002', 'VS', 30, '2021-01-01 11:00:00', '2021-01-01']]

but I wanted the output to be in like below
[['2020-02-08', 2, 0, '1002', 'VS', 30, '2021-01-01 11:00:00', '2021-01-01'],
['2020-02-08', 1, 0, '1001', 'PS', 20, '2021-01-01 10:00:00', '2021-01-01']
]

我尝试使用 sorted 和 key itemgetter,但我无法为每个元素指定顺序。

使用排序或任何其他方法解决此问题的任何想法?

1 个答案:

答案 0 :(得分:0)

from datetime import datetime

print(sorted(ll, key=lambda x: (datetime.strptime(x[6], "%Y-%m-%d %H:%M:%S"), x[4])))