我有一个2d列表,包含一些信息,如,并希望根据价格对列表进行排序,list[8]
flights = [
['22-04-02', 'TR980', '06:00', '09:50', 'Singapore(SIN)', 'HongKong(HKG)', 'Yes', '/', '148', '0', '500', '156'],
['22-04-03', 'TR980', '06:00', '09:50', 'Singapore(SIN)', 'HongKong(HKG)', 'Yes', '/', '148', '0', '500', '235'],
['22-04-04', 'TR980', '06:00', '09:50', 'Singapore(SIN)', 'HongKong(HKG)', 'Yes', '/', '148', '0', '500', '342'],
['22-04-05', 'TR980', '06:00', '09:50', 'Singapore(SIN)', 'HongKong(HKG)', 'Yes', '/', '148', '0', '500', '23'],
['22-04-06', 'MF852', '15:25', '19:30', 'Singapore(SIN)', 'Xiamen(XMN)', 'Yes', '/', '16841', '2x32kg', '500', '238']
]
def insertionSort(flights, key = lambda x: x):
for index in range(1, len(flights)):
currentValue = flights[index]
position = index
while position >0 and flights[position - 1] > currentValue:
flights[position] = flights [position -1]
position -= 1
flights[position] = currentValue
return flights
sorted_list = insertionSort(flights, key = lambda x: int(x[8]))
print(sorted_list)
但是排序后的列表只能按日期排序。
你得到了key
,但你从未使用过它。你应该比较key(...) > key(...)
key(flights[position - 1]) > key(currentValue)
与标准sorted()
相同
sorted_list = sorted(flights, key=lambda x: int(x[8]))