这是我的脚本。
# I have 100 variables
x0 = 3.14
x1 = 2.72
x2 = 1.41
x3 = 2.33
.... (omit this part)
x100 = 7.77
# xi corresponds to the value that the index i of a list needs to subtract,
# now I want to loop through the list
for i in range(100):
lst[i] -= 'x{}'.format(i)
这显然是行不通的,因为变量不是字符串。那么我应该如何对一个变量进行字符串格式化呢?
你可以通过以下方法访问这些变量 locals
:
lst[i] -= locals()['x{}'.format(i)]
为了获得变量的值,你可以使用Python的 评价函数
eval('x{}'.format(i))
还有,请千万不要把你的列表叫做变量列表。
编辑。 虽然这个解决方案在这种情况下是可行的,但建议尽量避免使用eval,因为它允许以一种你想不到的方式注入代码。
你应该使用 list
在这里。
x = [...]
(其中 x
拥有 len
(100人的)
然后为你的循环。
for i in range(100):
lst[i] -= x[i]
(重命名为 list
到 lst
以避免与内置类型发生名称碰撞)