如何将文本文件中包含数字的字符串从最大到最小排序?

时间:2017-12-31 19:54:18

标签: python python-3.x list file sorting

我有一个看起来像的文本文件:

Joe Smith: 200 dollars
Marcus: 150 dollars
Sally Mae: 300 dollars

等等。

我想要的是让它们在列表中从最大到最小排序,所以:

["Sally Mae: 300 dollars", "Joe Smith: 200 dollars", "Marcus: 150 dollars"]

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

您可以使用以下 lambda函数作为键的sorted函数来提取数字,然后对它们进行排序。

#                         v to only match numbers preceded with colon ':' and space
lambda x: int(re.search('(?<=:\s)\d+', x).group())
#          ^                       ^ match the pattern with continuing numbers
#          ^  type-cast the string of number to int
# `sorted` will use this returned int to sort the elements 

例如:

>>> import re
>>> my_list = ["Joe Smith32: 200 dollars", "Marcus: 150 dollars", "Sally Mae: 300 dollars"]

>>> sorted(my_list, key=lambda x: int(re.search('(?<=:\s)\d+', x).group()), reverse=True)
['Sally Mae: 300 dollars', 'Joe Smith32: 200 dollars', 'Marcus: 150 dollars']

默认情况下sorted按升序排序。使用reverse=True按降序排序。

要打开文件并将内容作为列表阅读,您只需要:

with open('/path/tofile.txt') as f:
    my_list = f.readlines()

注意:正如评论中所提到的,OP澄清说除了需要进行排序的数字之外,唯一可以出现这些数字的地方是用户名。因此,使用这个表达式是安全的。

答案 1 :(得分:0)

您可以尝试这样的事情:

import re
pattern=r'\d+'
sort_dict=[]
with open('file.txt','r') as f:
    for line in f:
        match=re.search(pattern,line)
        sort_dict.append((int(match.group()),line.strip()))
for i in sorted(sort_dict)[::-1]:
    print(i[1])

输出:

Sally Mae: 300 dollars
Joe Smith: 200 dollars
Marcus: 150 dollars