简体   繁体   English

如何使用 for 循环将不同的变量分配给 class object?

[英]How to assign different variables to a class object using for loop?

I want to use a for loop to make the code shorter.我想使用 for 循环来缩短代码。 In the following code I'm trying to create a chain of particles with same mass.在下面的代码中,我试图创建一个具有相同质量的粒子链。 Lets' say I want to create 50 particle.假设我想创建 50 个粒子。 " system.addParticle(mass)" will add one particle. “system.addParticle(mass)”将添加一个粒子。 So basically to need 50 particles I have to repeat this 50 times.所以基本上需要 50 个粒子,我必须重复 50 次。 Is there any way to use for loop for that?有什么方法可以使用 for 循环吗?


from simtk.openmm.app import *
from simtk.openmm import *
from simtk.unit import *
import numpy as np

mass = 1.0
system = System()
# This will add one particle
system.addParticle(mass)

I think this is equivalent:我认为这是等效的:

from simtk.openmm.app import *
from simtk.openmm import *
from simtk.unit import *
import numpy as np

# Taken from https://docs.python.org/3/library/itertools.html#itertools-recipes
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

new_pd = app.topology.Topology()

chain_new = new_pd.addChain()

residue_names = ['MET', 'THR', 'TYR', 'LYS', 'LEU']
residues = [new_pd.addResidue(name, chain_new) for name in residue_names]

atoms = [new_pd.addAtom('CA', 'C', res) for res in residues]

bonds = [new_pd.addBond(atom1, atom2) for atom1, atom2 in pairwise(atoms)]

Alternatively you could do something like:或者,您可以执行以下操作:

def add_atom(topology, chain, residue_name):
    residue = new_pd.addResidue(residue_name, chain)
    atom = new_pd.addAtom('CA', 'C', residue)
    return atom

atoms = []
for residue_name in ['MET', 'THR', 'TYR', 'LYS', 'LEU']:
    atoms.append(add_atom(new_pd, chain_new, residue_name))
bonds = # ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM