如何在Python中使用迴圈為列表中的變數賦值?
本文將討論使用Python迴圈為列表中的變數賦值的不同方法。
使用簡單的迴圈迭代
這種方法使用for迴圈將元素新增到列表中。當不再向列表中新增元素時,只需按回車鍵。
為了將元素新增到列表中,我們使用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
廣告