按字符串的第一个单词(数字)对字符串进行排序

时间:2021-05-11 20:29:06

标签: python sorting

场景

我们都知道尝试按字母顺序对数字进行排序的结果是

123, 234, 5, 76, 9

但是假设您有一个看起来像这样的字符串列表

123 Some title
234 Another title
5 More title
76 Titles abound
9 Last title

并且您希望按每个标题的第一个单词中的数字大小对其进行排序。

预期结果

5 More title
9 Last title
76 Titles abound
123 Some title
234 Another title

问题

有没有一种很好的方式来排序,要么通过不同的数据结构,要么通过其他方式?

详情

我想到了变成某种字典或相关数组,例如

5: More title,
//...

但数字对于我的用例来说不一定是唯一的。

2 个答案:

答案 0 :(得分:1)

在调用 sorted function 时使用 lambda。如果这些是您作为字符串列表读入的行:

lines = ['123 Some title', '234 Another title', '5 More title', '76 Titles abound', '9 Last title']

# split the string into columns by whitespace, then cast the first
# column to an integer, and use that value to sort the strings.
sorted_lines = list(sorted(lines, key=lambda x: int(x.split()[0])))

您可以使用字符串以空格分隔的事实,并且如果将其转换为整数,您希望按第一列排序。这会产生您想要的结果。

答案 1 :(得分:0)

您可以使用字典来存储您的标题和字典理解来对它们进行排序。

titles = {int(title.split()[0]):' '.join(title.split()[1:])for title in lst}
newTitles = {tup[0]:tup[1] for tup in sorted(titles.items())}