[英]Python:How do I print not only the final value after running the for statement, but also the middle output?
everybody. 每一个人。 I want to make a code with a different name every time the For Moon is executed.
每次执行For Moon时,我想使用不同的名称编写代码。
for i in range(10):
SD="Vega"+str(i)
print(SD)
print(SD)
After executing the code above The result is as follows: 执行完上面的代码后,结果如下:
Vega0
Vega1
Vega2
Vega3
Vega4
Vega5
Vega6
Vega7
Vega8
Vega9
Vega9
What should I do if I want to print a value not just for VD9 but also for VD2 after all the for statements have been executed in the code above? 如果在上述代码中执行了所有for语句后,我不仅要为VD9而且要为VD2打印值,该怎么办?
you can store all the SD values in a list and access it later via indexing. 您可以将所有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...
You should store the intermediate values somewhere. 您应该将中间值存储在某个地方。
stored_values = []
for i in range(10):
SD="Vega" + str(i)
stored_values.append(SD)
print(SD)
or if you just want them as a long string that looks just like a print statement 或者,如果您只是想将它们作为长字符串,就像打印语句一样
SD = ''
for i in range(10):
SD+="Vega" + str(i) + "\n"
print(SD)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.