简体   繁体   English

您如何处理在 Python 中生成许多变量或对象的任务?

[英]How do you approach the task of generating many variables or objects in Python?

So this is more of a general question (as opposed to one looking for a specific line of code).所以这更像是一个普遍的问题(而不是寻找特定代码行的问题)。 Let's say you have a repeated process that generates an output. What is usually the best practice for storing the output so that it is easily accessible and ideally stored by name, where name is a variable as well?假设您有一个生成 output 的重复过程。存储 output 的最佳做法通常是什么,以便它易于访问并理想地按名称存储,其中名称也是一个变量? For example, I may have something like:例如,我可能有这样的东西:

for i in range(5):
     output = i * 5
  • Is there a way to assign the output of each iteration of your loop to a variable?有没有办法将循环的每次迭代的 output 分配给一个变量? So that the variable name itself is produced by the loop.这样变量名本身就是由循环产生的。 For example "trial0" is equal to 0, "trial1" is equal to 5, "trial2" is equal to 10, etc... And thus after doing the loop, I have constructed 5 new variables that I can use later on.例如,“trial0”等于 0,“trial1”等于 5,“trial2”等于 10,等等……因此在执行循环后,我构建了 5 个新变量,以后可以使用。
  • Would you be able to do something similar with dictionaries so that the key of the dictionary is produced by the loop and the items within that key are the output values?您能否对字典做类似的事情,以便字典的键由循环生成,并且该键中的项目是 output 值?

In other words, what's the best way/best practice for storing the output of a repeated task and so that it is easily accessible and identifiable by something other than index value.换句话说,存储重复任务的 output 的最佳方法/最佳实践是什么,以便可以通过索引值以外的其他内容轻松访问和识别它。 I would like to easily refer to the output each time as opposed to referring it like list[1] or something.我想每次都轻松地引用 output,而不是像 list[1] 之类的那样引用它。

Not using a list makes no sense, since:不使用列表是没有意义的,因为:

output = []
for i in range(5):
     output.append(i * 5)

print(output[0])
print(output[1])
...
print(output[4])

...is fine. ...很好。

yes, you can use a dict to store each iteration output:是的,您可以使用dict来存储每次迭代 output:

output = {}

for i in range(5):
     output[i] = i * 5

and it is easily accessible, O(1) time complexity if you want to jump to a specific iteration output它很容易访问,O(1) 时间复杂度如果你想跳转到特定的迭代 output

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

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