可以在for循环中多次评估范围(len())吗?

发布于 2025-01-21 20:04:35 字数 365 浏览 0 评论 0原文

在一段时间内,条件可以迭代地重新评估。示例:

while i < len(nums):

最新的索引inums的最新长度均用于重新评估条件。

在循环中并非如此。示例:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

左秋 2025-01-28 20:04:35

在循环中不是这种情况

当您创建range对象时,这种情况 。 range不存储对nums的引用,它只需要整数即可。如果您有一个列表

ls = [0, 1, 2, 3]

,则可以编写:

for i in ls:
    ls.append(i)

循环将永远运行,因为您正在添加i i ls 和ls正在添加每次。不过,我不建议尝试使用它来实现您的目标。在这里使用段循环很有意义。

This is not the case within a for-loop

No. This is the case when you create a range object. range does not store a reference to nums it just takes the integer. If you had a list

ls = [0, 1, 2, 3]

Then you could write:

for i in ls:
    ls.append(i)

and the loop would run forever, because you are getting i from ls and ls 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.

夜吻♂芭芘 2025-01-28 20:04:35

您可以使用枚举(NUM)在列表中获取当前索引,如果列表更长的时间,仍然可以走得更远。

在下面的示例中,我使用随机的机会有机会在每次迭代中应用新项目。

>>> import random
>>>
>>> nums = ["a", "a"]
>>>
>>> for i, val in enumerate(nums):
...    if random.randint(0, 1)==0:
...       nums.append("b")
...    print(str(i)+":"+val)
...
0:a
1:a
2:b
3:b

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.

>>> import random
>>>
>>> nums = ["a", "a"]
>>>
>>> for i, val in enumerate(nums):
...    if random.randint(0, 1)==0:
...       nums.append("b")
...    print(str(i)+":"+val)
...
0:a
1:a
2:b
3:b
断爱 2025-01-28 20:04:35

您可以制作一个只需掩盖循环的生成器。

def range_len(lst):
    i = 0
    while i < len(lst):
        yield i
        i += 1

for i in range_len(nums):
    ...

这是毫无意义的,除了证明循环的可以在更改的迭代中迭代。它之所以起作用,是因为生成器中的lst是与nums相同的对象,因此其长度将在每次迭代中重新评估。

You could make a generator that simply hides a while loop.

def range_len(lst):
    i = 0
    while i < len(lst):
        yield i
        i += 1

for i in range_len(nums):
    ...

This is pointless except to demonstrate that a for loop can iterate over a changing iterable. It works because the lst within the generator is the same object as nums and so its length will be re-evaluated on each iteration.

沒落の蓅哖 2025-01-28 20:04:35

如果有必要使用的理由,而不是在此使用,则有一些想法:

如果目的是避免由于列表在运行时缩小的列表界限(我尚未对此进行测试),那么我会说在身体的关键部分处于重新评估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.

花想c 2025-01-28 20:04:35

您可以使用变量并为每个循环设置数组的长度

 nums = [1, 2 ,3 ,4]
 i=0
 array_length=len(nums)
 while i < array_length:
   nums.pop()
   print(nums)
   array_length=len(nums)

you can use a variable and set the length of the array for each loop

 nums = [1, 2 ,3 ,4]
 i=0
 array_length=len(nums)
 while i < array_length:
   nums.pop()
   print(nums)
   array_length=len(nums)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文