Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python列表/数组的输出正在重复这些值。我如何删除这个?_Python - Fatal编程技术网

python列表/数组的输出正在重复这些值。我如何删除这个?

python列表/数组的输出正在重复这些值。我如何删除这个?,python,Python,我希望我的代码将x结果存储在一个列表中。但是,它重复了x的值。我该如何解决这个问题 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) / (pr

我希望我的代码将x结果存储在一个列表中。但是,它重复了x的值。我该如何解决这个问题

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)
我的结果是:

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]
如何将列表设置为:

[4.5, 1.0, 3.0, 4.5]

你需要调整你的缩进

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)
list1=[1,3,2,0,4,0,12]
非零=[t表示列表1中的t,如果t!=0]
set_x=[]
num_x=0
对于枚举(zip(非零,非零[1:])中的i(上一个系数,下一个系数):
x=(下一个系数*3)/(上一个系数*2)
打印(f“x{i+1}={x}”)
num_x+=1

对于范围内的j(num_x):#
对于范围内的j(num_x):set_x.append(x)
为什么要运行此循环?这将基本上多次添加一个元素,这就是您在输出中得到的结果。@AmitVikramSingh我想不出其他方法将x的值与我在循环中得到的x的数量相加。但我该如何解决这个问题?我是python新手。只需删除范围(num_x)
中j的
。仅使用
set\u x.append(x)
。对于附加到列表中,您不需要使用另一个循环。好的。工作。非常感谢你!