如何在 Python 中使用迴圈為列表中的變數賦值?
本文將討論在 Python 中使用迴圈為列表中的變數賦值的不同方法。
使用簡單的迴圈迭代
在這種方法中,我們使用 for 迴圈將元素追加到列表中。當我們不再向列表中新增任何元素並停止追加時,只需按 Enter 鍵。
為了將元素追加到列表中,我們使用append()方法。
示例 1
以下是一個使用 append() 方法在 Python 中使用迴圈為列表中的變數賦值的示例。
L=[] while True: item=input("enter new item or press enter if you want to exit ") if item=='': break L.append(item) print ("List : ",L)
輸出
執行以上程式碼後,將獲得以下輸出。
enter new item or press enter if you want to exit 5 enter new item or press enter if you want to exit 9 enter new item or press enter if you want to exit 6 enter new item or press enter if you want to exit List : ['5', '9', '6']
示例 2
在下面的示例中,變數名在 exec 語句中被引入 -
var_names = ['one','two','three'] count = 1 for n in var_names: exec ("%s = %s" % (n, count)) count +=1 print ('The values assigned to the variables are:',one, two, three)
輸出
以下是上述程式碼的輸出 -
The values assigned to the variables are: 1 2 3
使用 globals() 方法
在下面的示例中,我們使用globals()內建方法。您可以使用globals()方法訪問全域性變數的字典。
globals()方法檢索當前全域性符號表的字典。符號表是編譯器維護的一種資料結構,其中包含程式所需的所有資訊。
示例 3
以下是一個使用globals()方法在 Python 中使用迴圈為列表中的變數賦值的示例。
var_names = ["one", "two", "three"] count = 1 for name in var_names: globals()[name] = count count += 1 print(one) print(two) print(three)
輸出
執行以上程式碼後,將獲得以下輸出。
1 2 3
廣告