通过第三个嵌套列表在Python中对深层嵌套列表进行排序

时间:2018-01-17 09:26:43

标签: python sorting

如果这是重复,那么我很乐意删除这个问题。

在python中,我有一个具有以下结构的列表,其中没有一个名称必须相同:

[[xy, ["Name 3", ["SubName 1", "SubName 2"]], 
      ["Name 1", ["NameSub 1", "NameSub 2"]], ...],
 [yz, ["Name 10", ["SubNamex 1", "SubNamex 2"]], 
      ["Name 6", ["NameSubx 1", "NameSubx 2"]], ...]]

我想首先按第一个索引“xy”和“yz”排序,然后按“名称x”对每个嵌套列表中的项进行排序。所以我的排序列表应如下所示:

[[xy, ["Name 1", ["NameSub 1", "NameSub 2"]],
      ["Name 3", ["SubName 1", "SubName 2"]], ...],
 [yz, ["Name 6", ["NameSubx 1", "NameSubx 2"]], 
      ["Name 10", ["SubNamex 1", "SubNamex 2"]], ...]]

我试过了:

mylist.sort(key=lambda x: x[1]) 

mylist.sort(key=itemgetter(2,1))

指数的不同变化,但没有成功。

2 个答案:

答案 0 :(得分:1)

首先,迭代数组,对内部嵌套元素进行排序,最后对外部元素进行排序。 代码如下:

library(ISLR)
library(FactoMineR)
data("NCI60")

df <- NCI60$data


pca_prcomp <- prcomp(df, scale. = T)
pca_facto <- FactoMineR::PCA(df, scale.unit = T, graph = F, ncp = 65)


# One column is missing

dim(pca_prcomp$x)
dim(pca_facto$ind$coord) 

# Values are similiare - but not the same

head(pca_prcomp$x[, 1:2])
head(pca_facto$ind$coord[, 1:2])


# Using scale function - does not return same values

pca_facto_scale <- PCA(scale(df), scale.unit = F, graph = F, ncp = 65)

head(pca_facto$ind$coord[, 1:2], 3)
head(pca_facto_scale$ind$coord[, 1:2], 3)

答案 1 :(得分:0)

试试这个: -

a =     [['xy', ["Name 3", ["SubName 1", "SubName 2"]],
            ["Name 1", ["NameSub 1", "NameSub 2"]]],
        ['yz', ["Name 10", ["SubNamex 1", "SubNamex 2"]], 
                ["Name 6", ["NameSubx 1", "NameSubx 2"]]]]
# a.sort(key = lambda x: x[1])
for i in a:
    i.sort(key = lambda x : x[1])
    print i[-1],',',i[:-1] #or you can do print i only