简体   繁体   English

是否可以使用循环将多个变量分配给python中的不同值

[英]Is it possible to use a loop to assign multiple variables to different values in python

I have seen duplicates of this, but the original question was never answered: is it possible to assign values to multiple variables using a loop or some other method that would be more efficient that writing out all the variables in hard code.我见过这样的重复,但最初的问题从未得到回答:是否可以使用循环或其他一些方法将值分配给多个变量,这些方法比用硬代码写出所有变量更有效。

NOTE: I do not want to use dictionaries or list, I want to use variables.注意:我不想使用字典或列表,我想使用变量。 My question is whether it is possible to assign multiple variables at once using a loop or other method, not using dictionaries.我的问题是是否可以使用循环或其他方法而不是使用字典一次分配多个变量。

If this is not possible just say so, but I really don't want to see another answer describing how to use lists or dictionaries.如果这是不可能的,就这么说吧,但我真的不想看到另一个描述如何使用列表或字典的答案。

Duplicates: Python: assigning multiple variables at once重复项: Python:一次分配多个变量

Assign Many Variables at Once, Python 一次分配多个变量,Python


DISCLAIMER : The global()[] function that I talk about here may have more uses/parameters/arguments, but I am just telling you what I know.免责声明:我在这里谈论的global()[]函数可能有更多的用途/参数/参数,但我只是告诉你我所知道的。 You can experiment with it on your own你可以自己试验一下


Ok, now that I have found the answer, I'll post it here for future members to view.好的,现在我已经找到了答案,我会把它贴在这里供以后的成员查看。 Note that, as mentioned above, this technique is seldom used, but it's great to know for those corner cases.请注意,如上所述,这种技术很少使用,但了解这些极端情况会很好。

The crucial function here is the global()[] function in which you input a string and it turns it into a variable name.这里的关键函数是global()[]函数,您可以在其中输入字符串并将其转换为变量名称。 You leave the () completely empty, and enter the string into the [] .您将()完全留空,然后将字符串输入[] Now, this may seem useless, but one thing you can do is,现在,这似乎没用,但你可以做的一件事是,

for i in range(100):
    global()["Var"+str(i)] = i

Now you have 100 variables of the form Var# where # is the number, and, in this case, the value of the variable.现在您有 100 个Var#形式的Var# ,其中 # 是数字,在本例中,是变量的值。 This is a very, very simple case, and because of this extra flexibility, there are several things you can do with this.这是一个非常非常简单的案例,由于这种额外的灵活性,您可以用它做几件事。

Again, you will probably use this very few times while programming in python, since using extra lists of strings and values and then using this to create variables is unnecessary and inefficient, but , in the right places, this can save you a lot of time.同样,在使用 Python 编程时,您可能会很少使用它,因为使用额外的字符串和值列表然后使用它来创建变量是不必要且低效的,但是,在正确的地方,这可以为您节省大量时间. Just comment if you have any questions since I am not that good at explaining things.如果您有任何问题,请发表评论,因为我不太擅长解释事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM