mercredi 24 janvier 2018

If loop inside a for loop when appending

Given 2 lists of numbers:

real_solutions_sols1 =  [-53.2909210236, -8.31658000998, 1.87689837129, 1.4]
real_solutions_sols2 =  [-21.1439685227, -19.2]

I would like the same code to rewrite the lists so that they contain numbers between 0.1 and 4.0:

real_solutions_sols1 =  [ 1.87689837129, 1.4]

For the second list, this is not possible, so I would like the code to return the intact list:

real_solutions_sols2 =  [-21.1439685227, -19.2]

The following code works for real_solutions_sols2:

real_roots_zero_to_four = []
for i in real_solutions_sols2:
   if (i >= 0.1) & (i <= 4.0):
      real_roots_zero_to_four.append(i)
   else:
     real_roots_zero_to_four = real_solutions_sols2

print 'real_roots_zero_to_four = ', real_roots_zero_to_four

The if condition is not satisfied, so we jump to the else statement.

real_roots_zero_to_four = [-21.14396852, -19.2]

However, for the first list it is looping indefinitely:

real_roots_zero_to_four = []
for i in real_solutions_sols1:
   if (i >= 0.1) & (i <= 4.0):
      real_roots_zero_to_four.append(i)
   else:
     real_roots_zero_to_four = real_solutions_sols1

print 'real_roots_zero_to_four = ', real_roots_zero_to_four

I am not sure why this is happening

Aucun commentaire:

Enregistrer un commentaire