gpt4 book ai didi

python - 对数组数组的复杂结构进行排序

转载 作者:太空狗 更新时间:2023-10-30 01:14:37 25 4
gpt4 key购买 nike

我正在寻找一种方法来对具有复杂结构的数组进行排序:

L=[[
[[1,1,1,1,1,1,1],1,56],
[[6,6,6,6,6,6,6],1,3],
[[3,3,3,3,3,3,3],1,54]],
[[[2,2,2,2,2,2,2],2,42],
[[5,5,5,5,5,5,5],2,6]]]

我想按最后一个元素(56、3、54 和 42、6)对其进行排序。我想要得到的是:

L=[[
[[6,6,6,6,6,6,6],1,3],
[[3,3,3,3,3,3,3],1,54],
[[1,1,1,1,1,1,1],1,56]],
[[[5,5,5,5,5,5,5],2,6],
[[2,2,2,2,2,2,2],2,42]]]

我已经试过了:L.sort(key=lambda x: x[0][0][2])但它不起作用...

我看过那些建议,但我还没有成功:

How to sort a list of lists by a specific index of the inner list?

任何帮助将不胜感激!提前致谢!

最佳答案

您可以使用itemgetter 对多个索引进行排序。
在这种情况下,对 L[i]

上的索引 1 进行排序,然后对索引 2 进行排序
import operator
for i in range(len(L)):
L[i] = sorted(L[i], key=operator.itemgetter(1, 2))

或更简单:

import operator
for s in L:
s.sort(key=operator.itemgetter(1, 2))

感谢@georg

输出:

[[[[6, 6, 6, 6, 6, 6, 6], 1, 3],
[[3, 3, 3, 3, 3, 3, 3], 1, 54],
[[1, 1, 1, 1, 1, 1, 1], 1, 56]],
[[[5, 5, 5, 5, 5, 5, 5], 2, 6],
[[2, 2, 2, 2, 2, 2, 2], 2, 42]]]

关于python - 对数组数组的复杂结构进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29230844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com