【问题标题】:Sort nested list by another list [duplicate]按另一个列表对嵌套列表进行排序[重复]
【发布时间】:2019-01-17 08:15:35
【问题描述】:

我有以下双重嵌套列表:

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]]]

【问题讨论】:

  • stackoverflow.com/questions/10695139/… 这仍然适用于您的列表
  • @Gigaflop 同意策略基本相同,但是我有一个列表列表,而不是元组列表
  • 元组和列表的寻址方式相同,例如(3, 4)[0] 是3,[3, 4][0] 是3。

标签: python


【解决方案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)!

【讨论】:

    【解决方案2】:

    你可以使用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]]]
    

    【讨论】:

    • 谢谢,这行得通。你能解释一下sum 在做什么吗?
    • @holastello sum 为每个子列表中出现"female""male" 的次数创建一个“分数”。这样,可以使用反映目标值频率的值来确定潜在的排序交换。
    猜你喜欢
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 2013-09-17
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多