1. 程式人生 > >動態變數名

動態變數名

最近的程式碼設計中, 需要用到動態變數名, 在此記錄下
以下程式碼在win 10, python3.6版本下通過驗證

In [1]: for i in range(4):
   ...:     exec(f'val{i} = {i+1}')
   ...:
In [2]: val0
Out[2]: 1

In [3]: val1
Out[3]: 2

In [4]: val2
Out[4]: 3

In [5]: val4
---------------------------------------------------------------------------
NameError                                 Traceback (
most recent call last) <ipython-input-5-dd17f4ed2c2a> in <module>() ----> 1 val4 NameError: name 'val4' is not defined

以上用法可以通過,但是把它放到函式體中就會報錯:

def test():
    for i in range(3):
        exec(f'val{i} = {i}')
    print(val0)
    print(val1)
    print(val2)
test()
#output
Traceback (
most recent call last): File "D:\datawork\ti\apps\temp_scripts\test.py", line 132, in <module> test() File "D:\datawork\ti\apps\temp_scripts\test.py", line 129, in test print(val0, end='-----\n') NameError: name 'val0' is not defined

解決辦法是使用locals()globals(), 使其變為區域性變數或全域性變數:

names =
locals() # names = globals() 這個也是OK的 def test1(): for i in range(3): names[f'val{i}'] = i print(val0) print(val1) print(val2) test1() # output 0 1 2