问题描述
我有两个列表,一个X和一个Y。我想让这些列表创建一个文件,其值写为x,y。
现在我可以让他们将其写入文件,但是它只是每个excel单元格中的单个值,我需要将其设为x,y。
这是到目前为止我得到的:
import random as rd
X = []
Y = []
npts = 1000
#print (rd.random()*1000.00)
L = range(npts)
for n in L:
x = (rd.random()*1000.00)
X.append(x)
y = (rd.random()*1000.00)
Y.append(y)
#print X
#print Y
import numpy as np
#print min(X)
#print max(X)
#print min(Y)
#print max(Y)
#print np.mean(X)
#print np.mean(Y)
Xsub = []
Ysub = []
mxSubX = (np.mean(X) + 100)
mnSubX = (np.mean(X) - 100)
mxSubY = (np.mean(Y) + 100)
mnSubY = (np.mean(Y) - 100)
#print mxSubX
#print mnSubX
#print mxSubY
#print mnSubY
for n in X:
if (n > mnSubX)and (n < mxSubX):
Xsub.append(n)
#print Xsub
for n in Y:
if (n > mnSubY)and (n < mxSubY):
Ysub.append(n)
#print Ysub
f = open('lab4.csv','w')
for n in Xsub:
f.write(Xsub,Xsub)
f.close()
编辑:
for n in Xsub:
f.write(Xsub,Xsub)
他是我尝试将这两个列表中的值作为x,y(逗号作为定界符)放在excel的同一单元格中。这不是一个好尝试。我想要的输出是这样的:
>Xsub value,Ysub value
>Xsub value,Ysub value
编辑2: 这就是工作的结果:
f2 = open('subXY.txt','w')
I2 = range(1000)
for i in I:
#print (str(Xsub[i]) + ',' + str(Ysub[i]))
f2.write(str(Xsub[i]) + ',' + str(Ysub[i]))
解决方法
创建Xsub
和Ysub
之后,可以通过以下方式在文件中写入对(Xsub[i],Ysub[i])
:
with open('lab4.csv','w') as f:
for x,y in zip(Xsub,Ysub):
f.write("%s,%s\n" % (x,y))