4 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
可用于獲取作用域中的所有變量。vars()
對于示例:
day_1 = 5
day_2 = 10
day_3 = 15
i = 2
selected_variable = vars()[f"day_{i}"]

TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
下面的代碼將打印出變量的值day_2
i =2
selected_variable = 'day_{}'.format(str(i))
exec("print(%s)" % selected_variable)

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超13個(gè)贊
您可以將值存儲在列表中,并用作索引來訪問一個(gè)框,因?yàn)榱斜硎菑?開始編制索引的ii-1
days = [5, 10, 15]
i = 2
selected_variable = days[i - 1]
您還可以在字典中關(guān)聯(lián)鍵/值,并從數(shù)字中獲取值
days = {
1: 5, 2: 10, 3: 15
}
i = 2
selected_variable = days[i]

TA貢獻(xiàn)2003條經(jīng)驗(yàn) 獲得超2個(gè)贊
正如評論中提到的,有幾個(gè)問題:
您可以定義字典:
day = {
"day_1": 5,
"day_2": = 10,
"day_3": = 15
}
selected_variable = day[f"day_{i}"]
數(shù)組
day = [
5,
10,
15
]
selected_variable = day[i]
IF 語句
day_1 = 5
day_2 = 10
day_3 = 15
if i == 1:
selected_variable = day_1
elif i == 2:
selected_variable = day_2
elif i == 3:
selected_variable = day_3
或(或)字典(在這種情況下,我最喜歡的)localsvars
day_1 = 5
day_2 = 10
day_3 = 15
selected_variable = locals()[f"day_{i}"]
添加回答
舉報(bào)