sorted()仅按第一个数字排序

use*_*859 3 python

我需要对表的第一列进行排序.它看起来像

6000 799 
7000 352
8000 345
9000 234
10000 45536 
11000 3436
1000 342
2000 123
3000 1235
4000 234
5000 233
Run Code Online (Sandbox Code Playgroud)

我希望第一列按升序排列,但它只按第一个数字排序,而不是整列的值,即

1000 342
10000 45536
11000 3436
2000 123
Run Code Online (Sandbox Code Playgroud)

但我想要

1000 342
2000 123
3000 1235
etc
Run Code Online (Sandbox Code Playgroud)

目前尝试:

SortInputfile=open("InterpBerg1","r")
line=SortInputfile.readlines()
line.sort()
map(SortOutputfile.write, line)
Run Code Online (Sandbox Code Playgroud)

bik*_*der 5

sortsorted功能支持一键参数,它允许你指定哪个应该被用来进行排序的关键.由于您需要数字排序顺序而不需要按字母顺序排序,因此需要提取第一列并将其转换为int:

SortInputfile=open("InterpBerg1","r")
line=SortInputfile.readlines()
line.sort(key=lambda line: int(line.split()[0]))
map(SortOutputfile.write, line)
Run Code Online (Sandbox Code Playgroud)

更简洁的版本可能是:

# read input file
with open(input_filename) as fh:
    lines = fh.readlines()

# sort lines
lines.sort(key=lambda line: int(line.split()[0]))

# write output file
with open(output_filename, 'w') as fh:
    fh.writelines(lines)
Run Code Online (Sandbox Code Playgroud)