按每个字符串中的数值对列表进行排序

时间:2018-02-10 01:41:26

标签: python list sorting

我希望能够对每个包含数值和单词的字符串进行排序。

lst = ["1 Make", "7 William", "35 In", "22 Collins's"]

期望的输出:

["1 Make",  "7 William", "22 Collins's", "35 In"]

使用sorted(lst)我得到:

["1 Make", "22 Collins's", "35 In", "7 William"]

1 个答案:

答案 0 :(得分:4)

这应该有效:

lst = ["1 Make", "7 William", "22 Collins's", "35 In"]

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

# ['35 In', "22 Collins's", '7 William', '1 Make']