gpt4 book ai didi

python - 使用字符串模板时如何将所有循环元素追加到单行中?

转载 作者:行者123 更新时间:2023-11-30 22:53:48 24 4
gpt4 key购买 nike

我尝试使用字符串模板为 example.py 创建一个模板,其中我替换 $i ["CA:"+$i+':'+""中的每个 for 循环元素]。它部分有效,但仅替换最后一个元素。

但是,我想以某种格式将所有值 append 在单行中。

例如:

我当前的脚本执行的操作如下:

for i in range(1,4):
#It takes each "i" elements and substituting only the last element
str='''s=selection( self.atoms["CA:"+$i+':'+" "].select_sphere(10) )

我得到的内容如下:

    s=selection( self.atoms["CA:"+3+':'+" "].select_sphere(10) )

我期待的是:

    s=selection ( self.atoms["CA:"+1+':'+" "].select_sphere(10),self.atoms["CA:"+2+':'+" "].select_sphere(10),self.atoms["CA:"+3+':'+" "].select_sphere(10) )

我的脚本:

import os
from string import Template
for i in range(1,4):

str='''
s=selection( self.atoms["CA:"+$i+':'+" "].select_sphere(10) )
'''
str=Template(str)
file = open(os.getcwd() + '/' + 'example.py', 'w')
file.write(str.substitute(i=i))
file.close()

我使用这两个脚本来获得我想要的输出:

import os
from string import Template
a=[]
for i in range(1,4):
a.append(''.join("self.atoms["+ "'CA:' "+str(i)+""':'+" "+"]"+".select_sphere(10)"))

str='''s=selection( $a ).by_residue()'''
str=Template(str)
file = open(os.getcwd() + '/' + 'example.py', 'w')
file.write(str.substitute(a=a))

with open('example.py', 'w') as outfile:
selection_template = '''self.atoms["CA:"+{}+':'+" "].select_sphere(10)'''
selections = [selection_template.format(i) for i in range(1, 4)]
outfile.write('s = selection({})\n'.format(', '.join(selections)))

最佳答案

一个问题是,您的代码会在 for 循环的每次迭代中覆盖该文件,因为它以 'w' 模式打开输出文件。这就是为什么您只能看到文件中的最后一个。

此外,我不会使用 string.Template 来执行这些替换。只需使用 str.format() 。生成选择列表并使用 str.join()产生最终的字符串:

with open('example.py', 'w') as outfile:
selection_template = 'self.atoms["CA:"+{}+":"+" "].select_sphere(10)'
selections = [selection_template.format(i) for i in range(1, 4)]
outfile.write('s = selection({})\n'.format(', '.join(selections)))

此处 selection_template 使用 {} 作为变量替换的占位符,并使用列表理解来构造选择字符串。然后使用字符串 ', ' 作为分隔符将这些选择字符串连接在一起,并将结果字符串插入到对 selection() 的调用中,再次使用 str.格式()

关于python - 使用字符串模板时如何将所有循环元素追加到单行中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38075232/

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