Python排序列表,跳过

2024-09-29 01:38:06 发布

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

我有一份清单:

list = ["S9_1-", "S10_E1-17", "S25_1-21", "S3_1-", "S5_1-"] 

如果我这样做print sorted(list),我会得到:

['S10_E1-17', 'S25_1-21', 'S3_1-', 'S5_1-', 'S9_1-']

有没有一种方法我可以忽略这些字母,这样就可以把它们分类为:

['S3_1-', 'S5_1-', 'S9_1-', 'S10_E1-17', 'S25_1-21']

Tags: 方法s3字母分类listsortedprint我会
2条回答
seq = ["S9_1-", "S10_E1-17", "S25_1-21", "S3_1-", "S5_1-"] 
sorted_seq = sorted(seq, key=lambda item: int(item.split("_")[0][1:]))
assert sorted_seq == ['S3_1-', 'S5_1-', 'S9_1-', 'S10_E1-17', 'S25_1-21']

您要查找的是sort中可选的key参数。您可以使用它来告诉python根据函数进行排序。在这种情况下,该函数可以表示为:

def mykey(s):
    parts = s.split("_",1)
    importantPart = splits[0]
    number = int(importantPart[1:])  # remove the "S"
    return number

当然,这可以表示为一个简单的lambda:

lambda s: int(s.split("_",1)[0][1:])

因此,你会得到以下结果:

In [21]: L = ['S10_E1-17', 'S25_1-21', 'S3_1-', 'S5_1-', 'S9_1-']

In [22]: sorted(L, key=lambda s: int(s.split("_",1)[0][1:]))
Out[22]: ['S3_1-', 'S5_1-', 'S9_1-', 'S10_E1-17', 'S25_1-21']

相关问题 更多 >