简体   繁体   中英

How to stop a nested loop iterating over a list in Python

I'm trying to build a list of "populations" based on two ranges and one list. The nested loop I've created doesn't stop, even though I specify where it should break (I've checked the length of the list used in the loop which is equal to 303). So the output is infinite: after it prints the population value for v=2, J=100 (maximum needed), it goes back to displaying v=0,J=0 value for population. How can i fix that? Here is the code:

from scipy.optimize import minimize_scalar
import math
import itertools

we=268.64
wexe=0.814
weye=-0.0017
Be=0.0568325
ae=0.0001969
ge=-0.00000047
De=1.02E-8
kb=1.38065E-23

energy_groundJ=[]
def energyJ (v,J):
    E = we*(v+0.5) + wexe*(v+0.5)**2 + weye*(v+0.5)**3 + Be*(J*(J+1)) - ae*(v+0.5)*(J*(J+1)) - De*(J*(J+1)) + ge*(J*(J+1))*(v+0.5)**2
    E_J=E*1.986E-23
    return E_J
for v in [0,1,2]:
    for J in range(0,101):
        E_J=energyJ(v,J)
        energy_groundJ.append(E_J) 

Population=[]
def population_ground():
    P=(2*J+1)*math.exp(-i/(kb*295))
    return P
for i in energy_groundJ:
    for v in [0,1,2]:
        for J in range(0,101):
            if i==303:
                break
            P=population_ground()
            Population.append(P)
            print("population at v = "+str(v)+" and J ="+str(J)+"  = "+str(P))

break only breaks you out of one "for" loop (the closest one/top of the stack), not multiple.
Since your other loops don't do anything before the check, you could do this:

for i in energy_groundJ:
    if i==303:
        break
    for v in [0,1,2]:
        for J in range(0,101):
            P=population_ground()
            Population.append(P)
            print("population at v = "+str(v)+" and J ="+str(J)+"  = "+str(P))

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