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

时间:2015-03-24 11:00:02

标签: python arrays

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

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?

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

1 个答案:

答案 0 :(得分:4)

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

上索引 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]]]
相关问题