使用特定方法对字符串列表进行排序 [英] Sorting a list of strings with a specific method
本文介绍了使用特定方法对字符串列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个这样的字符串列表
let's say i have a list of strings like this
L = ['5', '3', '4', '1', '2', '2 3 5', '2 4 8', '5 22 1 37', '5 22 1 22', '5 22 1 23', ....]
我该如何对列表进行排序,这样我就可以得到这样的东西:
How can i sort this list so that i would have something like this:
L = ['1', '2', '3','4', '5', '2 3 5', '2 4 8', '5 22 1 22', ' 5 22 1 23', '5 22 1 37', ...]
基本上,我需要根据2个字符串之间的第一个不同数字对列表进行排序
basically i need to order the list based on the first different number between 2 strings
推荐答案
您可以使用元组进行排序:
You could sort using a tuple:
L = ['5', '3', '4', '1', '2', '2 3 5', '2 4 8', '5 22 1 37', '5 22 1 22', '5 22 1 23']
result = sorted(L, key=lambda x: (len(x.split()),) + tuple(map(int, x.split())))
print(result)
输出
['1', '2', '3', '4', '5', '2 3 5', '2 4 8', '5 22 1 22', '5 22 1 23', '5 22 1 37']
这个想法是使用一个元组作为键,其中第一个元素是字符串中数字的数量,其余元素是数字的元组.例如对于'2 3 5'
,键是(3, 2, 3, 5)
The idea is to use as key a tuple where the first element is the amount of numbers in the string and the rest is the tuple of numbers. For example for '2 3 5'
the key is (3, 2, 3, 5)
如@ PM2Ring所建议,您可以使用def
函数代替lambda
:
As suggested by @PM2Ring you could use a def
function instead of a lambda
:
def key(x):
numbers = tuple(map(int, x.split()))
return (len(numbers),) + numbers
这篇关于使用特定方法对字符串列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文