【问题标题】:Sorting a list of lists by the index of a sublist in python根据python中子列表的索引对列表列表进行排序
【发布时间】:2013-04-15 20:29:18
【问题描述】:

我在一个较大的脚本中间,需要按子列表的索引对列表进行排序。我的根列表包含对应于 [纬度、经度、海拔、距离] 的数字子列表。我需要在子列表中按距离对根列表进行排序。有什么想法吗?

【问题讨论】:

标签: python list indexing sublist


【解决方案1】:

您可以使用operator.itemgetter 根据列表中的元素对列表进行排序:

import operator
lst = [...]
lst.sort(key=operator.itemgetter(3))

【讨论】:

    【解决方案2】:

    您需要明确说明您希望列表排序的值是什么;在您的情况下,您的列表中每个元素的第 4 个元素。一种方法是使用sort 方法的key 关键字参数,并将提取该元素的函数(lambda)传递给它:

    >>> l = [[1,2,3,3],[1,2,3,2],[1,2,3,1]]
    >>> l.sort(key=lambda s: s[3])
    >>> l
    [[1, 2, 3, 1], [1, 2, 3, 2], [1, 2, 3, 3]]
    >>> 
    

    【讨论】:

    • len("lambda s: s[3]") => 14; len("operator.itemgetter(3)") => 22
    猜你喜欢
    • 2018-07-08
    • 1970-01-01
    • 2023-03-05
    • 2016-01-14
    • 1970-01-01
    • 2021-07-14
    • 2015-07-25
    • 2021-09-24
    • 1970-01-01
    相关资源
    最近更新 更多