2015-04-07 40 views
0

所以我有下面的代码,它是计算变化x和y的z值。它为我提供了50组值。问题是,如何将它保存在50列的外部文件中?在Python中保存一列数据集

import numpy as np 
x = np.linspace(0, 50, 51) 
y = np.linspace(100, 150, 51) 

for i in range(len(x)): 
    z = y-x[i] 

print z 

with open("output_data.csv","w") as out_file: 
    for i in range(len(x)): 
     out_string="" 
     out_string+=str(x[i]) 
     out_string += "," + str(z[i]) 
     out_string += "\n" 
     out_file.write(out_string) 

到目前为止,它不仅节省了第一组值

+1

尝试移动你的第一个for循环立即在“with open”块之下。然后在第一个for循环块下面立即移动你的第二个for循环(作为嵌套for循环)。 –

+0

是的,试了一下,但只给了我在同一列的值。紧随其后。你知道我怎样才能把它保存在不同的列中的每个z值? – Mac

回答

1

的问题是这一行的:

out_string += ", " + str(z[i]) 

您需要将此更改为:

out_string += ", ".join((str(_z) for _z in z))