如何更改每次循环进行时分配给数据的变量?

2024-06-06 12:21:33 发布

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

这是程序的示例

hello1,hello2,hello3,hello4,hello5=(),(),(),(),()
a_list=[hello1,hello2,hello3,hello4,hello5]
greetingslist= ["hello","good morning","good evening","afternoon","hi"]
for i range 5:
    a_list[i]=greetingslist[i]

所以我希望每个变量标识符都是不同的,这样每个变量都可以被赋值。但是,它无法识别变量旁边的[i],因此会发生错误

我不想改变程序太多或使它太复杂,但我想这是在一个循环内完成…有没有任何办法,我可以做到这一点

提前谢谢


Tags: 程序示例hellohilistgoodmorningevening
1条回答
网友
1楼 · 发布于 2024-06-06 12:21:33

您只是存储对变量的引用,在循环中重写它。如果要按名称动态设置变量,则必须根据名称空间使用globals()/locals()/setattr(),例如:

greetings_list = ["hello", "good morning", "good evening", "afternoon", "hi"]

for i, v in enumerate(greetings_list):
    locals()["hello" + str(i + 1)] = v

print(hello1)  # hello
print(hello2)  # good morning
print(hello3)  # good evening
print(hello4)  # afternoon
# etc.

并不是说这是一个推荐的风格或任何东西,远离它,但这就是你可以做到的

相关问题 更多 >