首页 > 解决方案 > 如何将文件从最低到最高排序,包括负数?

问题描述

我想按升序对这两个文件进行排序,包括负值。

值.txt =

-0.0059
0.0716
-0.0058
-0.0059
-0.1139
-0.1139
-0.0312
-0.0759
-0.0341
0.0047
-0.1813
-0.185
-0.06585
-0.023
-0.1438
0.05921
0.0854
-0.2039
-0.1813
0.05921

字符.txt =

man
king
new
one
text
gorilla
zilla
dulla
mella
killa
anw
testing
worry
no
time
test
kiss
queue
mouse
like

预期输出 - 这是我希望收到的代码

queue   -0.20399
testing -0.185
mouse   -0.181378
anw -0.1813
time    -0.1438
text    -0.1139
gorilla -0.1139
dulla   -0.0759
worry   -0.06585
mella   -0.0341
zilla   -0.0312
no  -0.023
man -0.0059
one -0.0059
new -0.0058
killa   0.0047
like    0.05921
test    0.0592104
king    0.0716
kiss    0.08544

我的代码:我尝试构建此代码,但它不会工作

with open("all.txt", "w+") as outfile:
        value= open("value.txt","r").read().splitlines()
        character= open("character.txt","r").readlines()
        a = sorted(list(zip(value,character)))
        for x in a:
            line = " ".join(str(uu) for uu in x)
            outfile.write("{}".format(line))

不知何故,我的输出是这样的错误:

-0.0058 new
-0.0059 man
-0.0059 one
-0.023 no
-0.0312 zilla
-0.0341 mella
-0.06585 worry
-0.0759 dulla
-0.1139 gorilla
-0.1139 text
-0.1438 time
-0.1813 anw
-0.181378 mouse
-0.185 testing
-0.20399 queue
0.0047 killa
0.05921 like
0.0592104 test
0.0716 king
0.08544 kiss

我尝试了许多其他方法,但仍然无法使其成为预期的输出。谁能帮助我。

标签: pythonsorting

解决方案


这是一种方法。

演示:

with open(filename) as infile, open(filename1) as infile_1:
    value =  [float(line.strip()) for line in infile.readlines()]
    character =  [line.strip() for line in infile_1.readlines()]

data = zip(value, character)
for i in sorted(data, key=lambda x: x[0], reverse=True)[::-1]:
    print( "{1} = {0}".format(*i) )

输出:

queue = -0.2039
testing = -0.185
mouse = -0.1813
anw = -0.1813
time = -0.1438
gorilla = -0.1139
text = -0.1139
dulla = -0.0759
worry = -0.06585
mella = -0.0341
zilla = -0.0312
no = -0.023
one = -0.0059
man = -0.0059
new = -0.0058
killa = 0.0047
like = 0.05921
test = 0.05921
king = 0.0716
kiss = 0.0854

推荐阅读