[英]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
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.