如何将文件从最低到最高排序,包括负数?

2024-10-03 15:33:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想对这两个文件进行升序排序,包括负值。你知道吗

你知道吗值.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

我尝试了许多其他的方法,但仍然不能使它达到预期的效果。谁能帮我一下吗。你知道吗


Tags: notexttxtnewtestingonemangorilla
2条回答

我不知道这是不是最有效的方法。但是如果我继续关注您的代码,我会添加几行代码来转换value中的项:

with open("all.txt", "w+") as outfile:
        value= open("value.txt","r").read().splitlines()
        # additional 2 lines:
        for i in range(len(value)):
            value[i] = float(value[i])
        character= open("character.txt","r").readlines()
        a = sorted(list(zip(value,character)))
        print(a)
        for x in a:
            line = " ".join(str(uu) for uu in x)
            outfile.write("{}".format(line))

这是一种方法。你知道吗

演示:

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

相关问题 更多 >