python sort itemgetter等效于N维嵌套列表

标签 python list python-2.7 sorting multidimensional-array

要在 python 2.7 中按第二维的第 n 个元素对嵌套二维列表 (list2D) 进行排序,我可以使用

import operator
sorted(list2D, key=operator.itemgetter(n))

如何根据第二个和第三个维度的第 n 个元素对 3D 列表 (list3D) 的第二个维度进行排序?

这将对下面的 list3D 进行排序,目前顺序为 4,7,2。

list3D = [[[5,4,5,7],
           [0,1,1,0]],
          [[2,7,5,7],
           [1,0,0,1]],
          [[1,2,5,7],
           [1,1,1,0]]]

进入下面的 sort3D,它按第二和第三维的索引 [0][1] 排序为 2,4,7

sort3D = [[[1,2,5,7],
           [1,1,1,0]],
          [[5,4,5,7],
           [0,1,1,0]],
          [[2,7,5,7],
           [1,0,0,1]]]

最佳答案

sorted()可以接受一个将被赋予一个元素的 lambda,并且应该返回一些可排序的东西(这里是你的值)来对结果进行排序:

>>> list3D = [[[5,4,5,7],
               [0,1,1,0]],
              [[2,7,5,7],
               [1,0,0,1]],
              [[1,2,5,7],
               [1,1,1,0]]]
>>> sorted(list3D, key=lambda x: x[0][1])
[[[1, 2, 5, 7], [1, 1, 1, 0]], [[5, 4, 5, 7], [0, 1, 1, 0]], [[2, 7, 5, 7], [1, 0, 0, 1]]]

文档有一个 great appendix关于使用 key=

关于python sort itemgetter等效于N维嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35217920/

相关文章:

python - 需要 : simple way to force json to decode to "normal" iterable python lists

python - Pycharm:将文件夹标记为 'sources root' 对于子文件夹不是递归的

python - 我如何根据用户提出的问题使用变量做公式

python - 具有固定和有序键的可变字典

Python 遍历列表中的滑动窗口对?

python - 语音队列寻找句子中口语单词的重复部分

python - 我如何列一个 list

python - 正则表达式匹配所有非字母,不包括变音符号(python)

python - Python输入 “-”

python - 处理文件的正确方法?