简体   繁体   中英

Multiple python append functions in while loop crashing

Attempting to print a composite list by appending item from three smaller lists in sequence:

def final_xyz_lister():
    global final_xyz_list
    final_xyz_list = []
    step=0
    while step==0:
        final_xyz_list.append(carbon_final_list[step]) 
        final_xyz_list.append(oxygen_final_list[step]) 
        final_xyz_list.append(hydrogen_final_list[step]) 
        step=+1
    while 0 < step < 50:   
        final_xyz_list.append(carbon_final_list[step]) 
        final_xyz_list.append(oxygen_final_list[step]) 
        final_xyz_list.append(hydrogen_final_list[step]) 
        step=+1
    else:
        pass   

If I comment out the second while loop the first element of the list is printed in a list as expected but introduction of the second while loop results in a MemoryError.

There is no need to append the three items in 2 different while loops. It would also be simpler if you used for loops. in this case:

for step in range(0, 50):
    final_xyz_list.append(carbon_final_list[step]) 
    final_xyz_list.append(oxygen_final_list[step]) 
    final_xyz_list.append(hydrogen_final_list[step]) 

Edit: Also, I just noticed the error, you use step =+ 1 , which is the same as saying step = +1 or step = 1 . This is why you are getting a memory error, you keep defining step as 1, which is between 0 and 50, so the while loop just keeps going. what you probbly wanted to write was step += 1 , this increases step by 1 and doesn't set it to 1

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