![](/img/trans.png)
[英]How can I print a variables stored in a dictionary to screen using a for loop?
[英]How can i print the value of the variables ??(note: the variables were declared as global variable using a for loop)
如何自動打印變量的值(從 w1 到 w5),而不是單獨鍵入命令 print(w1) 到 print(w5)?
i = 0
for j in range(5):
i += 1
globals()["w"+str(i)] = list(range(1,20))
print(w1)
print(w2)
print(w3)
print(w4)
print(w5)
不太明白你將如何使用
for x in range(1, 5): print(globals()[f"w{x}"])
在問題的代碼中,沒有變量w
。 它只是字符串的一部分。
如果要將w
設置為具有可調用元素的變量,則將其用作列表,如下所示:
w = [] # set w to an empty list
for j in range(5):
w.append(j) # fill the list
# print the whole list
print(w)
# print one element from the list
print(w[2])
這將返回:
[0, 1, 2, 3, 4]
2
作為額外說明,您可以使用 global 關鍵字將變量設為global
變量,但這通常用於 function 內部的 scope。
w = [0,1,2,3,4]
def some_function():
global w
print('inside function:', w)
some_function()
這將返回:
inside function: [0, 1, 2, 3, 4]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.