我的代码
import itertools
import os
with open("base.txt") as fv, open("new2.txt", 'r') as fi, open('sortedf.txt','w') as fs:
vel = (line.strip() for line in fv)
ind = (int(line.strip()) for line in fi)
z = itertools.izip(ind, vel) # sort according to ind
# itertools.izip(vel, ind) # sort according to vel
for i, v in sorted(z):
fs.write(str(v))
我把所有东西放在一行
2.900000e+032.900000e+032.900000e+032.900000e+032.
当我换到
fs.write('\n'.join(str(v)))
然后我得到了
2
.
9
0
0
0
0
0
e
+
0
32
.
9
0
0
0
0
0
e
+
0
32
.
如何逐行获取正确的值?
答案 0 :(得分:2)
只需改变
for i, v in sorted(z):
fs.write(str(v))
到
for i,v in sorted(z):
print(v, file=fs)
\n
的end="\n"
默认参数, print
会自动添加
适用于任何数据类型。无需str(v)
答案 1 :(得分:1)
请尝试以下
fs.writelines(map(lambda x: x[1], sorted(z)))
为什么以下声明失败
fs.write('\n'.join(str(v)))
这里将v转换为列表,并在其上应用连接。为清晰起见,请查看以下示例
>>> sam = 'hello'
>>> '-'.join(sam)
'h-e-l-l-o'
那么如何使用fs.write?
很少有建议:
import os # load important modules first
from itertools import izip # makes processing faster, if you only need izip
with open("base.txt") as fv, open("new2.txt", 'r') as fi, open('sortedf.txt','w') as fs:
vel = [line.strip() for line in fv] # use square braces
ind = int(line.strip()) for line in fi] # use square braces
z = izip(ind, vel) # sort according to ind
for i, v in sorted(z):
fs.write(v)
fs.write('\n') # adding line break