在文件列表中写入一个点列表

时间:2016-02-15 21:17:09

标签: python-3.x

我有100分,我想将它们从10个参考点分成10个不同的组,并将每个组写在一个文件中。 我把我的程序写成:

from numpy import *
from math import *
from time import *
a=1.0
b=1.0
nx=10     # number of mesh in x
ny=10     # number of mesh in y
dx=a/nx
dy=b/ny
data=loadtxt("cvt_squate.txt",float)
n=data.shape

fids = []
for i in range(n[0]):
    ii=str(i)
    fids.append(open('file' + ii + '.txt', 'w'))

def calculateDistance(x1,y1,x2,y2):
     dist = sqrt((x2 - x1)**2 + (y2 - y1)**2)
     return dist

for i in range(nx) :
    for j in range(ny) :
        distance=10.0
        grain=1000
        x=(i+0.5)*dx
        y=(j+0.5)*dy
        for k in range (n[0]):   
            d = calculateDistance(x,y,data[k,0],data[k,1])
            if d<distance:
                distance=d
                grain=k
        print(grain)
        kk=str(grain)
        outdata = vstack((x,y)).T
        savetxt('file' + kk + 'txt', outdata)

但是在我的结果中,我在每个文件中都有一个点而不是一组点。

1 个答案:

答案 0 :(得分:0)

如果没有任何样本数据,很难看出代码应该如何工作。但首先我建议将导入重写为:

import numpy as np 
import math

我看不到你在哪里使用时间模块。

如果您将结果定义为For k循环外的列表,并将参考点附近的所有点追加到此列表中。类似的东西:

outdata = []
for k in range(n[0]):   
    d = calculateDistance(x,y,data[k,0],data[k,1])
    if d<distance:
        outdata.append([data[k,0],data[k,1]])

应该让你更接近你想去的地方。