如何字符串格式化变量?

这是我的脚本:

# 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):
    list[i] -= 'x{}'.format(i)

这显然不起作用,因为变量不是字符串。那么我应该如何对变量进行字符串格式化?

评论
xnemo
xnemo

You should instead use a list here.

x = [...] (where x has a len of 100)

然后为您的循环:

for i in range(100):
    lst[i] -= x[i]

(Renamed list to lst to avoid name collision with the built-in type)

点赞
评论
哼小曲
哼小曲

You can access these variables using locals:

list[i] -= locals()['x{}'.format(i)]
点赞
评论
hea
hea

In order to get the value of the variable, you can use Python's eval function

eval('x{}'.format(i))

而且,请不要调用您的列表变量列表

点赞
评论