2024-09-29 01:38:06 发布
网友
我有一份清单:
list = ["S9_1-", "S10_E1-17", "S25_1-21", "S3_1-", "S5_1-"]
如果我这样做print sorted(list),我会得到:
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']
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根据函数进行排序。在这种情况下,该函数可以表示为:
sort
key
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']
您要查找的是
sort
中可选的key
参数。您可以使用它来告诉python根据函数进行排序。在这种情况下,该函数可以表示为:当然,这可以表示为一个简单的lambda:
因此,你会得到以下结果:
相关问题 更多 >
编程相关推荐