Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何更改每次循环进行时分配给数据的变量?_Python_Variables - Fatal编程技术网

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

Python 如何更改每次循环进行时分配给数据的变量?,python,variables,Python,Variables,这是程序的示例 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] 所以我希望每个变量标识符都是不同的,这样每个变量都可以被赋

这是程序的示例

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]
,因此会发生错误

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


提前谢谢

您只是存储对变量的引用,在循环中重写这些变量。如果要按名称动态设置变量,则必须根据名称空间使用
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.

并不是说它是一种推荐的样式或任何东西,远非如此,而是你可以这样做。

除非真的有必要,否则我建议你使用python字典。简短的回答是,不要这样做