1

我正在尝试将数据写入下一个文件,但在中途下,更改列的一个值,该值对于第一组行是恒定的。这是我的代码:

import random
import time

start_time = time.time() #time measurement
numpoints = 512
L = 20
d = 1
points = set()

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

我的代码目前以这种格式生成一个 XYZ 文件

512 #number of
comment goes here
H 6.000000 19.000000 14.000000
H 11.000000 2.000000 7.000000
H 15.000000 20.000000 16.000000

我在这里先向您的帮助表示感谢!

编辑,抱歉,这就是我想要实现的

512 #number of
comment goes here
H 6.000000 19.000000 14.000000
H 11.000000 2.000000 7.000000
H 15.000000 20.000000 16.000000
O 6.000000 19.000000 14.000000
O 11.000000 2.000000 7.000000
O 15.000000 20.000000 16.000000

现在我的代码将 H 作为所有 512 行的第一个值,从第 256 行开始,我需要将其更改为 O

4

1 回答 1

2

您可以使用生成器生成点和两个for循环:

def pointgen(used):
    while True:
        p = (random.randint(0, L), random.randint(0, L), random.randint(0, L))
        if p not in used:
            used.add(p)
            yield p

# Open f and write
with open("question2.xyz","w") as f:
    f.write("%d\ncomment goes here\n" % numpoints) #this is for the 2nd line in my xyz 
    pg = pointgen(points)
    for i in xrange(numpoints // 2):
        f.write('H %f %f %f\n' % pg.next())
    for i in xrange(numpoints // 2):
        f.write('O %f %f %f\n' % pg.next())
于 2012-10-03T08:34:07.177 回答