将带有编号方案的变量附加到lis时出现问题

2024-04-25 04:22:55 发布

您现在位置:Python中文网/ 问答频道 /正文

a1 = 0
a2 = 1

x = [] #here I have declared an empty list
for i in range(2):
    x.append('a'+str(i+1)) #to append the variable with a numbering scheme
print (x)

这是一个示例python代码。我在编程任务中遇到的类似情况。你知道吗

这里的输出是['a1','a2'],而我需要的输出是[0,1]。有人能帮我吗?你知道吗


Tags: thetoinana2forherehave
3条回答

如果必须使用作用域中已有的变量,则可以使用locals()将所有局部变量作为dict获取

a1 = 0
a2 = 1

x = [] #here I have declared an empty list
for i in range(2):
    x.append(locals()['a'+str(i+1)]) #to append the variable with a numbering scheme
print (x)

为此使用词典:

d = {'a1': 0, 'a2':1}
x = [] #here I have declared an empty list
for i in range(2):
    x.append(d['a'+str(i+1)]) #to append the variable with a numbering scheme
print (x)

vars = {
    'a1': 0,
    'a2': 1,
}

x = []

for var in vars.keys():
    x.append(vars[var])

print(x)

相关问题 更多 >