按内部列表的特定索引对列表进行排序

时间:2016-05-14 13:28:46

标签: python list sorting python-3.x

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

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

因为这个原因我无法根据这些整数值对列表进行排序。

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

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

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

1 个答案:

答案 0 :(得分: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,']]
相关问题