我必须订购从最短到最长的数字列表。长度相等,按升序排列。
input=[[19, -3, 2, -10, -20], [22, 2, -10, -20], [19, -3, 12, -20], [19, -3, 2, 10], [20, -10, -20], [22, 12, -20], [22, 2, 10], [30, -20], [20, 10], [50], [10], [10, -20], [22, 32], [30], [19, -3, 32]]
预期输出:
[(10,), (30,), (50,),
(10, -20), (20, 10), (22, 32), (30, -20),
(19, -3, 32), (20, -10, -20), (22, 2, 10), (22, 12, -20),
(19, -3, 2, 10), (19, -3, 12, -20), (22, 2, -10, -20),
(19, -3, 2, -10, -20)]
答案 0 :(得分:1)
似乎您需要按 length 和元组本身进行排序才能获得预期的结果:
input_lst = [[19, -3, 2, -10, -20], [22, 2, -10, -20], [19, -3, 12, -20], [19, -3, 2, 10], [20, -10, -20], [22, 12, -20], [22, 2, 10], [30, -20], [20, 10], [50], [10], [10, -20], [22, 32], [30], [19, -3, 32]]
res = sorted(input_lst, key=lambda x: (len(x), x))
print(res)
输出:
[[10], [30], [50], [10, -20], [20, 10], [22, 32], [30, -20], [19, -3, 32], [20, -10, -20], [22, 2, 10], [22, 12, -20], [19, -3, 2, 10], [19, -3, 12, -20], [22, 2, -10, -20], [19, -3, 2, -10, -20]]
如果实际上需要获取结果作为元组列表,则将关键行更改为以下内容:
res = sorted(map(tuple, input_lst), key=lambda x: (len(x), x))
答案 1 :(得分:1)
您寻找的答案是
sorted(input, key=lambda l: (len(l), l))
答案 2 :(得分:0)
只需使用自定义键对其进行排序,该键将根据子列表的长度进行排序,并将列表的值用于相同长度的列表
>>> input.sort(key=lambda l: (len(l), l))
>>> print (*input, sep='\n')
[10]
[30]
[50]
[10, -20]
[20, 10]
[22, 32]
[30, -20]
[19, -3, 32]
[20, -10, -20]
[22, 2, 10]
[22, 12, -20]
[19, -3, 2, 10]
[19, -3, 12, -20]
[22, 2, -10, -20]
[19, -3, 2, -10, -20]