我有以下双重嵌套的列表:
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]]]
答案 0 :(得分:1)
这可能比您要的要复杂一些。我假设:
您不能保证每个组仅包含一个“ list_order”类别中的项目
您希望最终列表加倍嵌套,将所有“ 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
答案 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]]]