我的任务是在一个尺寸为 20x20x20 的盒子内生成随机坐标(其中 512 个)。
查看此 3D 图像的程序需要 XYZ 文件,其格式为:
1000.000000 #number of coordinates
comment goes here #coment line
H 0.000000 0.000000 0.000000 #1st colmun is arbitary - we'll leave it H, 2nd is x vavlue, 3rd value is y value and 4th column is z value.
H 0.000000 0.000000 1.000000
H 0.000000 0.000000 2.000000
H 0.000000 0.000000 3.000000
到目前为止,我有,
import random
numpoints=512
L=20
while len(points)<numpoints:
p = (random.randint(0, L), random.randint(0, L), random.randint(0, L))
if p not in points:
points.add(p)
这将生成我的 (x,y,z) 坐标,但我遇到的问题是将它放入文本文件中。
我从这样的事情开始,但需要一些帮助:
with open("question1.xyz","w") as file:
file.write("\ncomment goes here\n") #this is for the 2nd line in my xyz file
while len(points)<numpoints:
p = (random.randint(0, L), random.randint(0, L), random.randint(0, L))
if p not in points:
points.add(p)
file.write('H %f %f %f\n' % (x, y, z))
这就是我必须创建我的输出并将行数放在第一行但出于某种原因它不会模仿我的文件
#this will put the number of particles as the first line and generate an output file
with open("question2.xyz") as infile:
with open("q2Output.xyz","w") as outfile:
for i,line in enumerate(infile):
if i==0:
outfile.write('%f\n'%counter)
else:
outfile.write(line)
我发现它是因为我的计数器不存在,但是有没有更有效的方法呢?