Python 使用循环来命名变量

Python 使用循环来命名变量,python,Python,所以我想知道如何在python中实现这一点: X = int(input("How many students do you want to add? ")) for X: studentX = str(input("Student Name: ")) 有什么想法吗?你没有。您可以使用列表来代替: how_many = int(input("How many students do you want to add? ")) students = [] for i in range(ho

所以我想知道如何在python中实现这一点:

X = int(input("How many students do you want to add? "))
for X:
    studentX = str(input("Student Name: "))

有什么想法吗?

你没有。您可以使用列表来代替:

how_many = int(input("How many students do you want to add? "))
students = []
for i in range(how_many):
    students.append(input("Student Name: "))

一般来说,您。

我对Martijn的答案投了赞成票,但是如果您需要类似于变量名的东西,您可以通过student1调用studentX,您可以使用一个对象:

how_many = int(input("How many students do you want to add? "))
students = {}
for i in range(how_many):
    students["student{}".format(i+1)] = input("Student Name: ")

我不打算提出解决方案…

简短回答:你不能轻易做到,但你可以使用字典。如果你真的想这么做,你可以开始破解
globals()
,但这是一个非常糟糕的问题idea@C.B.:好吧,你可以,至少对globals是这样,但你真的不想这么做。因为下一件事你们知道你们想要解决那个些变量,你们必须再次生成那个些名称。一次又一次。使用列表或字典时,您不必担心这些。@MartijnPieters说得很好。如果我能以自己为例,我的第一个Python专业项目涉及从几百台机器获取文件大小信息。我们担心清除过程没有正确运行。我使用
globals()。这意味着我现在不知道如何维护这个脚本,如果我因为任何原因不得不修复它,上帝会帮助我。注意,
I
0
开始,而不是
1
,所以你把
student0
转到
student
。你的意思肯定是
I+1
,而不是
-
。当然,很尴尬。我还接受了@s16h建议的编辑