简体   繁体   English

按第三个嵌套列表对Python中的深层嵌套列表进行排序

[英]Sorting Deep Nested lists in Python by third nested list

If this is a duplicate, then I'd be glad to delete the question. 如果这是重复的,那么我很乐意删除问题。

In python, I have a list that has the following structure, with none of the names necessarily being the same: 在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"]], ...]]

I want to sort first by the first index, "xy" and "yz", and then sort the items with each nested list by "Name x". 我想首先按第一个索引“ xy”和“ yz”进行排序,然后按“名称x”对每个嵌套列表的项目进行排序。 So my sorted list should look like this: 所以我的排序列表应如下所示:

[[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"]], ...]]

I have tried: 我努力了:

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

and

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

and different variations of the indices, with no success. 以及索引的不同变体,都没有成功。

First, iterate the array sorting the inner nested elements and finally sort the outer elements. 首先,对数组进行迭代以对内部嵌套元素进行排序,最后对外部元素进行排序。 The code is provided below: 下面提供了代码:

srtli=[]
for ele in li:
    tmp=ele[1:]
    tmp.sort()
    for ele_tmp in tmp:
        ele_tmp[1].sort()
    srtli.append([ele[0]]+tmp)
srtli.sort()

try with this :- 试试这个:-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM