I want my code to store the x results in a list. However, it is repeating the value of x's. How do I fix this?
list = [1, 3 , 2, 0, 4, 0, 12]
non_zeros = [list for list in list if list != 0]
set_x = []
num_x = 0
for i, (prev_coeff, next_coeff) in enumerate(zip(non_zeros, non_zeros[1:])):
x = (next_coeff*3) / (prev_coeff*2)
print(f"x{i + 1} = {x}")
num_x += 1
for j in range(num_x):
set_x.append(x)
print(set_x)
My result is:
x1 = 4.5
x2 = 1.0
x3 = 3.0
x4 = 4.5
[4.5, 1.0, 1.0, 3.0, 3.0, 3.0, 4.5, 4.5, 4.5, 4.5]
How do I set the list to be:
[4.5, 1.0, 3.0, 4.5]
you need to adjust your indentation
list1 = [1, 3 , 2, 0, 4, 0, 12]
non_zeros = [t for t in list1 if t != 0]
set_x = []
num_x = 0
for i, (prev_coeff, next_coeff) in enumerate(zip(non_zeros, non_zeros[1:])):
x = (next_coeff*3) / (prev_coeff*2)
print(f"x{i + 1} = {x}")
num_x += 1
for j in range(num_x): #<--- indent this outside of your loop
set_x.append(x)
print(set_x)
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.