Python:4个循环,比较列表项

时间:2012-10-18 22:17:33

标签: python cycle

我有一个非常可怕的算法来比较原子之间的距离,但它不起作用我想让它起作用。这是代码:

for k in ResListA:
  for n in ResListB:
    for m in ResListA[counter3].atoms:
        for z in ResListB[counter4].atoms:
            coordDist = distance.distance(ResListA[counter3].atoms[counter4],ResListB[counter2].atoms[counter1])
            counter1 = counter1 + 1
        counter1 = 0         
        counter4 = counter4 + 1 
    counter4 = 0
    counter2 = counter2 + 1
  counter2 = 0
  counter3 = counter3 + 1

基本上我想要

之间的最小距离
  

ResListA [0] .atoms [0,..,N]

     

ResListB [0,..,K] .atoms [0,..,M]

要计算。但是,它会计算

  

ResListA [0] .atoms [0]

  

ResListB [0,..,K] .atoms [0,..,M]

例如:

  

ResListA [N,P,C,N,C] ResListB [C,C] [P,P] ...

应该是

  

dist(N,C)dist(N,C)dist(P,C)dist(P,C)

不是

  

dist(N,C)dist(N,C)dist(N,P)dist(N,P)

提前谢谢。

2 个答案:

答案 0 :(得分:2)

我认为您的代码可以写得更像这样。

for k in ResListA:
    for n in ResListB:
        for m in k.atoms:
            for z in n.atoms:
                coordDist = distance.distance(m.atoms, z.atoms)

不知道distance.distance做了什么。你不应该对涉及coordDist的{​​{1}}做些什么吗?

答案 1 :(得分:0)

虽然gnibbler可能是正确的,但这就是你当前的代码简化为:

for k in ResListA:
    for n in ResListB:
        for counter4, m in enumerate(k.atoms):
            for counter1, z in enumerate(ResListB[counter4].atoms):
                coordDist = distance.distance(m, n.atoms[counter1])

你的问题是你需要:

for z in ResListB[counter2].atoms:

而不是

for z in ResListB[counter4].atoms: