gpt4 book ai didi

python - 将数据写入文本文件然后中途更改

转载 作者:行者123 更新时间:2023-12-01 05:55:41 25 4
gpt4 key购买 nike

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

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

最佳答案

您可以使用生成器来生成点,并使用两个 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())

关于python - 将数据写入文本文件然后中途更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12704418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com