簡體   English   中英

我如何打印變量的值??(注意:變量被聲明為使用 for 循環的全局變量)

[英]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.

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