0

我的任务是在一个尺寸为 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)

我发现它是因为我的计数器不存在,但是有没有更有效的方法呢?

4

2 回答 2

2

这可以进一步清理,但所做的基本更改是:

  1. 添加points容器
  2. 更改filef(您希望避免定义与 Python 内置同名的变量),
  3. 更改格式参数以接受元组p(它将自动解包)
  4. 进行一些基本的格式更改。

总而言之,你们非常接近——只是需要调整一些基本的东西。

import random

numpoints = 512
L = 20
points = set()

# Open f and write
with open("question1.xyz","w") as f:
    f.write("\ncomment goes here\n") #this is for the 2nd line in my xyz f
    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)
            f.write('H %f %f %f\n' % p)

以下内容不再有效,但引入了递归的概念以生成随机点。以前的版本工作得很好 - 这更有趣:)

import random

numpoints = 512
L = 20
points = set()

def RandomPoint(points):
    p = (random.randint(0, L), random.randint(0, L), random.randint(0, L))
    if p in points:
      p = RandomPoint(points)
    return p

# Open f and write
with open("question1.xyz","w") as f:
    f.write("\ncomment goes here\n") #this is for the 2nd line in my xyz f
    for point in xrange(0, numpoints):
        p = RandomPoint(points)
        points.add(p)
        f.write('H %f %f %f\n' % p)
于 2012-10-03T04:30:18.793 回答
1

尝试这样的事情:

fh = open('filename', 'w')
fh.write(str(len(points)) + '\n')
fh.write("comment goes here\n")
for point in points:
    fh.write("H %1.6f %1.6f %1.6f\n" % (point[0],point[1],point[2]))
fh.flush()
fh.close()
于 2012-10-03T04:22:04.923 回答