可以在for循环中多次评估范围(len())吗?
在一段时间内,条件可以迭代地重新评估。示例:
while i < len(nums):
最新的索引i
和nums
的最新长度均用于重新评估条件。
在循环中并非如此。示例:
for i in range(len(nums)):
此处range(len(nums))
是被创建的,即使nums
更改的长度也保持不变(例如,由于循环中的弹出值)。我对这个过程的理解是否正确?有没有办法使循环取决于“移动目标帖子”(更改nums
长度)?
Within a while-loop the condition get's iteratively re-evaluated. Example:
while i < len(nums):
Both the latest index i
and the latest length of nums
are used to re-evaluate the condition.
This is not the case within a for-loop. Example:
for i in range(len(nums)):
Here range(len(nums))
is created and remains unchanged even when the length of nums
changes (e.g., due to popping values within the loop). Is my understanding of this process correct? Is there a way to make the for-loop dependent on 'a moving goal post' (the changing nums
length)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当您创建
range
对象时,这种情况 。range
不存储对nums
的引用,它只需要整数即可。如果您有一个列表,则可以编写:
循环将永远运行,因为您正在添加
i
i ls 和ls
正在添加每次。不过,我不建议尝试使用它来实现您的目标。在这里使用段循环很有意义。No. This is the case when you create a
range
object.range
does not store a reference tonums
it just takes the integer. If you had a listThen you could write:
and the loop would run forever, because you are getting
i
fromls
andls
is being added to each time. I would not recommend trying to use this to achieve your goal, though. Using a while loop makes sense here.您可以使用枚举(NUM)在列表中获取当前索引,如果列表更长的时间,仍然可以走得更远。
在下面的示例中,我使用随机的机会有机会在每次迭代中应用新项目。
You could use enumerate(nums) to iterate through the list getting the current index and still go further if the list gets longer.
In the following example i used random to have a chance of applying a new item with every iteration.
您可以制作一个只需掩盖
时
循环的生成器。这是毫无意义的,除了证明循环的
可以在更改的迭代中迭代。它之所以起作用,是因为生成器中的
lst
是与nums
相同的对象,因此其长度将在每次迭代中重新评估。You could make a generator that simply hides a
while
loop.This is pointless except to demonstrate that a
for
loop can iterate over a changing iterable. It works because thelst
within the generator is the same object asnums
and so its length will be re-evaluated on each iteration.如果有必要使用的理由,而不是在此使用,则有一些想法:
如果目的是避免由于列表在运行时缩小的列表界限(我尚未对此进行测试),那么我会说在身体的关键部分处于重新评估len(n)并相应打破的条件。
如果意图是继续使用for循环,以防长度扩展,那么我可能会考虑嵌套循环,而外部循环却是在破坏条件下为true(如果我达到len(n))。在这种情况下,内部循环的起始值并不总是为零。
If there is a necessary reason to use for and not while then here are some ideas:
If the intent is to avoid running out of list boundaries as a result of the list shrinking at runtime (I have not tested this), then I would put a condition at that critical part of the body to reassess i against len(n) and break accordingly.
If the intent is to continue with the for loop in case the length expands, then maybe I would consider nested loops with the outer being while True with a breaking condition (if i reaches len(n)). In that case the starting value of the inner loop will not always be zero.
您可以使用变量并为每个循环设置数组的长度
you can use a variable and set the length of the array for each loop