請幫幫我,我堅持將 lopping 輸出分配給一個變數
這是我的代碼
a = [0.5, 0.0, 1.2, 2.4, 0.1, 3.5]
for obs in a:
if obs > 0:
print('2')
elif obs < 0.1:
print('1')
輸出是
2
1
2
2
2
2
我想將該輸出保存到變數中
uj5u.com熱心網友回復:
IIUC,將結果存盤在串列'b'中,如下例所示
a = [0.5, 0.0, 1.2, 2.4, 0.1, 3.5]
b=[]
for obs in a:
if obs > 0:
b.append(2)
elif obs < 0.1:
b.append(1)
print(b)
[2, 1, 2, 2, 2, 2]
uj5u.com熱心網友回復:
您可以在回圈之外創建一個變數并將值保存在那里,或者對于更“pythonic 方式”,您可以使用串列理解
b = [1 if i <0.1 else 2 for i in a]
b 是:
[2, 1, 2, 2, 2, 2]
uj5u.com熱心網友回復:
如果我了解您要正確執行的操作,最簡單的方法是使用另一個串列并將輸出附加到該串列中。
像這樣的東西:
a = [0.5, 0.0, 1.2, 2.4, 0.1, 3.5]
#Output list that will be written to
output = []
for obs in a:
if obs > 0:
#Adds '2' to the end of the output list
output.append('2')
elif obs < 0.1:
#Adds '1' to the end of the output list
output.append('1')
#Loop to print the contents of output
for n in output:
print(n)
輸出將是:
2
1
2
2
2
2
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/489170.html
