簡體   English   中英

我的 python 列表/數組的 Output 重復這些值。 我該如何刪除這個?

[英]Output of my python list / array is repeating the values. How do I remove this?

我希望我的代碼將 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM