Python排序列表的列表,其中包含整数和内部带有整数的字符串 [英] Python sort list of list containing integer and string with integers inside
本文介绍了Python排序列表的列表,其中包含整数和内部带有整数的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何使用python对列表格式进行排序
How i can use python to sort the list format
format=["12 sheet","4 sheet","48 sheet","6 sheet", "busrear", "phonebox","train"]
喜欢这种方式
format =["4 sheet", "6 sheet", "12 sheet", "48 sheet", "busrear", "phonebox", "train"]
答案在这里 Python排序的字符串数组,其中包含整数
但是,如果数组是列表的列表,那么我们该如何做到这一点
but If the array is a list of list then how can we do that like this one
format=[[1, '12 sheet', 0],[2, '4 sheet', 0], [3, '48 sheet', 0], [4, '6 sheet', 0 [5, 'Busrear', 0], [6, 'phonebox', 0], [7, 'train', 0]]
我需要结果像这样
format=[[2, '4 sheet', 0],[4, '6 sheet', 0],[1, '12 sheet', 0],[3, '48 sheet', 0],[5, 'Busrear', 0], [6, 'phonebox', 0], [7, 'train', 0]]
推荐答案
您可以执行以下操作:
lst = [[1L, u'12 sheet', 0],
[2L, u'4 sheet', 0],
[3L, u'48 sheet', 0],
[4L, u'6 sheet', 0],
[5L, u'Busrear', 0],
[6L, u'phonebox', 0],
[7L, u'train', 0]]
def sortby(x):
try:
return int(x[1].split(' ')[0])
except ValueError:
return float('inf')
lst.sort(key=sortby)
print lst
输出:
[[2L, u'4 sheet', 0], [4L, u'6 sheet', 0], [1L, u'12 sheet', 0], [3L, u'48 sheet', 0], [5L, u'Busrear', 0], [6L, u'phonebox', 0], [7L, u'train', 0]]
您始终可以使用更出色的列表理解功能,但可读性很重要.这就是为什么您可能不想修改很酷的解决方案由falsetru完成此任务.
You can always use fancier list comprehension but readability counts. Which is why you might not feel like modifying the cool solution by falsetru for this slightly changed task.
这篇关于Python排序列表的列表,其中包含整数和内部带有整数的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文