不使用sorted()方法对2d列表进行排序

时间:2020-03-14 06:54:30

标签: python list

我正在尝试对该2d列表进行排序

arr = [['Potato', 10, 'House'], ['Salad', 9, 'not'], ['few', 4, 'and']]

排序后,它应该像这样:

[['few', 4, 'and'], ['Salad', 9, 'not'],  ['Potato', 10, 'House']]

我尝试使用最小数字作为arr[0][1],然后遍历列表,但无法获取。

不使用sorted()或sort()

3 个答案:

答案 0 :(得分:2)

按关键参数排序

print(sorted(arr, key=lambda x:x[1]))
# [['few', 4, 'and'], ['Salad', 9, 'not'], ['Potato', 10, 'House']]

答案 1 :(得分:2)

sorted()的工作原理与其他答案相同,并且列表本身具有sort()方法:

>>> arr = [['Potato', 10, 'House'], ['Salad', 9, 'not'], ['few', 4, 'and']]
>>> 
>>> arr.sort(key=lambda x: x[1])
>>> arr
[['few', 4, 'and'], ['Salad', 9, 'not'], ['Potato', 10, 'House']]
>>> 

sorted()返回一个新的排序列表,而<list>.sort()对该列表进行排序。

答案 2 :(得分:2)

您可以在下面尝试此操作

from operator import itemgetter

arr = [['Potato', 10, 'House'], ['Salad', 9, 'not'], ['few', 4, 'and']]
print(sorted(arr, key=itemgetter(1)))