按子字符串排序字符串列表

2024-10-02 12:34:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我要把这张单子分类

list = ['16. Michlík', '4. and 65. Bichakhchyan', '15. Pavol']

根据每个字符串的第一个数字。所以输出应该是这样的

list = ['4. and 65. Bichakhchyan', '15. Pavol', '16. Michlík']

这是我到目前为止所做的,但是当字符串中有一个以上的数字时,它就不起作用了

sorted(list, key=lambda x : x[:x.find(".")])

你们能帮帮我吗?你知道吗


Tags: andlambdakey字符串分类数字findlist
3条回答

必须将模式强制转换为整数,否则将其作为字符串进行比较。你知道吗

sorted(list, key=lambda x : int(x[:x.find(".")]))

您可以使用正则表达式:

import re
l = ['16. Michlík', '4. and 65. Bichakhchyan', '15. Pavol']
result = sorted(l, key=lambda x:int(re.findall('^\d+', x)[0])) 

输出:

['4. and 65. Bichakhchyan', '15. Pavol', '16. Michlík']

这是一种方法。你知道吗

lst = ['16. Michlík', '4. and 65. Bichakhchyan', '15. Pavol']

res = sorted(lst, key=lambda x: int(x.split('.')[0]))

# ['4. and 65. Bichakhchyan', '15. Pavol', '16. Michlík']

相关问题 更多 >

    热门问题