[英]Sorting a txt file containing strings and numbers in python
I want to sort a txt file containing both strings and numbers by ascending numbers.我想按升序对包含字符串和数字的 txt 文件进行排序。 example of a file:
文件示例:
Berlin 400
London 903
Oslo 905
Washington 300
So for example I want this file to be sorted by ascending number, like this:例如,我希望这个文件按升序排序,如下所示:
Washington 300
Berlin 400
London 903
Oslo 905
How do I do this?我该怎么做呢?
Say you have a file capitals.txt
with the following contents:假设您有一个包含以下内容的文件
capitals.txt
:
Berlin 400
London 903
Oslo 905
Washington 300
You could consider parsing the data into a list of namedtuples
before sorting and writing the list to an output file:在对列表进行排序并将其写入输出文件之前,您可以考虑将数据解析为
namedtuples
元组列表:
from collections import namedtuple
CapitalInfo = namedtuple('CapitalInfo', 'name num')
capitals = []
with open('capitals.txt', 'r') as capitals_file:
for row in capitals_file:
name, num_str = row.split()
num = int(num_str)
capitals.append(CapitalInfo(name, num))
capitals.sort(key=lambda c: (c.num, c.name))
with open('sorted_capitals.txt', 'w') as sorted_capitals_file:
for name, num in capitals[:-1]:
sorted_capitals_file.write(f'{name} {num}\n')
name, num = capitals[-1]
sorted_capitals_file.write(f'{name} {num}')
What sorted_capitals.txt
contents are after running above:上面运行后
sorted_capitals.txt
内容是什么:
Washington 300
Berlin 400
London 903
Oslo 905
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.