简体   繁体   中英

Python: 4 for cycles, comparing list items

I have a quite scary algorithm to compare distances between atoms, however it works not the i want it to work. Here is the code:

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

Basically i want that minimal distance between

ResListA[0].atoms[0,..,n]

ResListB[0,..,k].atoms[0,..,m]

to be calculated. However, it calculates

ResListA[0].atoms[0]

to

ResListB[0,..,k].atoms[0,..,m]

For example:

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

It should be

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

not

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

Thank you in advance.

I think your code can be written more like this.

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)

no idea what distance.distance does. Shouldn't you be doing something with coordDist involving min() ?

While gnibbler is probably correct in that is what you should do, this is what your current code simplifies to:

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])

Your problem is that you need:

for z in ResListB[counter2].atoms:

instead of

for z in ResListB[counter4].atoms:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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