【问题标题】:sort list of lists by specific index of inner list按内部列表的特定索引对列表进行排序
【发布时间】:2016-09-10 16:04:14
【问题描述】:

我正在尝试对文件执行一些操作并将其行转换为列表。但是整数值也被视为字符串

l1 = [['test', 'hello', '60,'], ['why', 'to', '500,'], ['my', 'choice', '20,']]

因此,我无法根据这些整数值对列表列表进行排序。

有没有办法可以将所有这些list[2] 值转换为整数并根据它对外部列表进行排序?或者我可以使用上面列表中的整数对该列表进行排序的任何其他方式。

预期结果是,排序列表的输出应显示为:

[['my', 'choice', '20,'], ['test', 'hello', '60,'], ['why', 'to', '500,']]

【问题讨论】:

    标签: python list sorting python-3.x


    【解决方案1】:

    使用自定义排序键,仅在排序时将最后一个元素转换为整数:

    sorted(l1, key=lambda l: int(l[2].rstrip(',')))
    

    key 用于为列表中的每个元素生成要排序的值。所以对每个元素调用lambda函数,上面的代码提取l[2]值,将其转换为整数。 str.rstrip() 调用首先删除结尾的逗号。

    演示:

    >>> l1 = [['test', 'hello', '60,'], ['why', 'to', '500,'], ['my', 'choice', '20,']]
    >>> sorted(l1, key=lambda l: int(l[2].rstrip(',')))
    [['my', 'choice', '20,'], ['test', 'hello', '60,'], ['why', 'to', '500,']]
    

    【讨论】:

    • 非常感谢,它成功了:) // 又一个查询,现在这个列表按升序排序,降序排序怎么办?
    • @Zoro99:将reverse=True 添加到sorted() 调用中。
    猜你喜欢
    • 2011-05-09
    • 1970-01-01
    • 2018-01-30
    • 2017-04-08
    • 2015-07-25
    • 2022-01-08
    • 2011-03-16
    • 2022-01-18
    相关资源
    最近更新 更多