我正在尝试将数据写入下一个文件,但是然后中途向下,更改前一列的一个值,该值对于第一组行是常量。这是我的代码:
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
答案 0 :(得分: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())