[英]Python:How do I print not only the final value after running the for statement, but also the middle output?
每一個人。 每次執行For Moon時,我想使用不同的名稱編寫代碼。
for i in range(10):
SD="Vega"+str(i)
print(SD)
print(SD)
執行完上面的代碼后,結果如下:
Vega0
Vega1
Vega2
Vega3
Vega4
Vega5
Vega6
Vega7
Vega8
Vega9
Vega9
如果在上述代碼中執行了所有for語句后,我不僅要為VD9而且要為VD2打印值,該怎么辦?
您可以將所有SD值存儲在列表中,以后再通過索引進行訪問。
list_sd = [] # initialize empty list
for i in range(10):
SD="Vega"+str(i)
print(SD) # prints "Vega1", "Vega2" etc.
list_sd.append(SD) # appends the respective SD value to your list
print(SD) # prints the last VD, "Vega9" in this case
print(list_sd[i]) # i being the index, so list_vd[1] prints "Vega1" and so on...
您應該將中間值存儲在某個地方。
stored_values = []
for i in range(10):
SD="Vega" + str(i)
stored_values.append(SD)
print(SD)
或者,如果您只是想將它們作為長字符串,就像打印語句一樣
SD = ''
for i in range(10):
SD+="Vega" + str(i) + "\n"
print(SD)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.