按另一个列表对嵌套列表进行排序

时间:2018-08-09 19:09:05

标签: python

我有以下双重嵌套的列表:

records = [[['Jack', 'male', 1],['Jack', 'male', 2],['Jack', 'male', 3]],[['Sally', 'female', 1],['Sally', 'female', 2],['Sally', 'female', 3]]]

我想根据此列表对该列表进行排序...

list_order = ['female', 'male']

...这样的结果是:

records 
[[['Sally', 'female', 1],['Sally', 'female', 2],['Sally', 'female', 3]],[['Jack', 'male', 1],['Jack', 'male', 2],['Jack', 'male', 3]]]

2 个答案:

答案 0 :(得分:1)

这可能比您要的要复杂一些。我假设:

  1. 您不能保证每个组仅包含一个“ list_order”类别中的项目

  2. 您希望最终列表加倍嵌套,将所有“ list_order”类别分组在一起

  3. 除了与“ list_order”匹配的一列外,没有其他顺序
  4. 项目应完全按照它们在“ list_order”中列出的顺序

因此,您可以使用以下代码:

records = [[['Jack', 'male', 1],['Jack', 'male', 2],['Jack', 'male', 3]],[['Sally', 'female', 1],['Sally', 'female', 2],['Sally', 'female', 3]]]
list_order = ['female', 'male']

# "flatten" list into singly-nested list
records = [leaf for branch in records for leaf in branch]

# sort the items in the list by list_order 
# sorted passes each item in the list to the lambda function
# record[1] is the position of "male"/"female"
records = sorted(records, key=lambda record: list_order.index(record[1]))

# group the list by list_order again, creating doubly-nested list
records = [ [record for record in records if record[1] == item ] for item in list_order ]

print records

Try it online (with debugging printouts)!

答案 1 :(得分:0)

您可以使用sum

records = [[['Jack', 'male', 1],['Jack', 'male', 2],['Jack', 'male', 3]],[['Sally', 'female', 1],['Sally', 'female', 2],['Sally', 'female', 3]]]
list_order = ['female', 'male']
new_records = sorted(records, key=lambda x:sum(list_order.index(i[1]) for i in x))

输出:

[[['Sally', 'female', 1], ['Sally', 'female', 2], ['Sally', 'female', 3]], [['Jack', 'male', 1], ['Jack', 'male', 2], ['Jack', 'male', 3]]]