4 回答
TA贡献1828条经验 获得超3个赞
可用于获取作用域中的所有变量。vars()
对于示例:
day_1 = 5
day_2 = 10
day_3 = 15
i = 2
selected_variable = vars()[f"day_{i}"]
TA贡献1773条经验 获得超3个赞
下面的代码将打印出变量的值day_2
i =2
selected_variable = 'day_{}'.format(str(i))
exec("print(%s)" % selected_variable)
TA贡献1842条经验 获得超12个赞
您可以将值存储在列表中,并用作索引来访问一个框,因为列表是从0开始编制索引的ii-1
days = [5, 10, 15]
i = 2
selected_variable = days[i - 1]
您还可以在字典中关联键/值,并从数字中获取值
days = {
1: 5, 2: 10, 3: 15
}
i = 2
selected_variable = days[i]
TA贡献2003条经验 获得超2个赞
正如评论中提到的,有几个问题:
您可以定义字典:
day = {
"day_1": 5,
"day_2": = 10,
"day_3": = 15
}
selected_variable = day[f"day_{i}"]
数组
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}"]
添加回答
举报