iT邦幫忙

0

python 流水號變數

之前打某個程式碼時
剛好要設流水號變數
那時用eval
但會出現can't assign to function call

for i in range(1, 11):
    eval(f'index{i}') = [i]
  File "<ipython-input-1-e1edd69b53c4>", line 2
    eval(f'index{i}') = [i]
    ^
SyntaxError: can't assign to function call

不過這用法蠻冷門的
有這需求時
大部分會直接放在list

解決辦法用globals()[str]
範例

for i in range(1, 11):
    globals()[f'index{i}'] = [i]
    print(f'index{i} =', eval(f'index{i}'))

輸出

index1 = [1]
index2 = [2]
index3 = [3]
index4 = [4]
index5 = [5]
index6 = [6]
index7 = [7]
index8 = [8]
index9 = [9]
index10 = [10]

尚未有邦友留言

立即登入留言