Python根据for循环索引创建变量 [英] Python create variable according to for loop index

查看:35
本文介绍了Python根据for循环索引创建变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 for 循环的每次迭代创建变量:

I am trying to create variable for each iteration of the for loop:

for i in range(10):
x(i) = 'abc'

for i in range(10):
x(i) = 'abc'

这样我就可以得到 x1, x2, x3, x4, .... x10, 都等于 'abc'

so that I would get x1, x2, x3, x4, .... x10, all equal to 'abc'

有人知道怎么做吗?谢谢!

Anyone know how to do it? Thanks!

推荐答案

你不应该那样做,如果你想通过名字访问它们,将你的值存储在 dict>list 如果你想通过索引访问它们,但如果你真的坚持:

You should not be doing that, store your values in a dict if you want to access them by name, or a list if you want to access them by index, but if you really insist:

for i in range(10):
    locals()["x" + str(i)] = "abc"  # use globals() to store the vars in the global stack

print(x3)  # abc

这篇关于Python根据for循环索引创建变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆