【问题标题】:Python List Sorting using lambda function使用 lambda 函数的 Python 列表排序
【发布时间】:2020-08-20 08:50:12
【问题描述】:

我有一个[[['foo', '$total', 400], ['foo', 'sauce', 300], ['foo', 'bacon', 100]], [['bar', 'bro', 200], ['bar', '$total', -200], ['bar', 'sup', -400]]] 的列表

我想应用一个排序列表理解,这样“$total”在列表中排在第一位,列表的其余部分按照列表中的第三项进行排序。

输出示例:[[['foo', '$total', 400], ['foo', 'sauce', 300], ['foo', 'bacon', 100]], [['bar', '$total', -200], ['bar', 'bro', 200], ['bar', 'sup', -400]]]

这里“$total”根据所有子列表排在第一位,列表的其余部分根据最后/第三个元素进行反向排序。

我试过了,但没有用:

 for index, ele in enumerate(final_res):
    final_res[index] = list(sorted(final_res[index], key=lambda x: [ x[1] if x[1] == "total" else x[2] ], reverse=True))

请让我知道通过列表理解排序实现这一目标的最佳方法是什么。

【问题讨论】:

    标签: python python-3.x list sorting list-comprehension


    【解决方案1】:

    使用自定义函数

    例如:

    data = [[['foo', '$total', 400], ['foo', 'sauce', 300], ['foo', 'bacon', 100]], [['bar', 'bro', 200], ['bar', '$total', -200], ['bar', 'sup', -400]]] 
    for i in data:
        i.sort(key=lambda x: (x[1] == '$total', x[2]), reverse=True)
    print(data)
    #OR data = [sorted(i, key=lambda x: (x[1] == '$total', x[2]), reverse=True) for i in data]
    

    输出:

    [[['foo', '$total', 400], ['foo', 'sauce', 300], ['foo', 'bacon', 100]],
     [['bar', '$total', -200], ['bar', 'bro', 200], ['bar', 'sup', -400]]]
    

    【讨论】:

      猜你喜欢
      • 2020-10-25
      • 1970-01-01
      • 2019-12-29
      • 1970-01-01
      • 2012-11-26
      • 2014-04-12
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多