如何对文件从最低到最高排序(包括否定)?

时间:2018-08-20 07:21:39

标签: python sorting

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

Value.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

Character.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

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

2 个答案:

答案 0 :(得分:2)

这是一种方法。

演示:

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

答案 1 :(得分:0)

我不知道这是否是最有效的方法。但是,如果我要靠近您的代码,我会添加几行来转换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))