有没有一种方法可以迭代指定次数而不引入不必要的变量?

发布于 2024-09-15 02:47:22 字数 333 浏览 6 评论 0原文

如果我想在 Java 中迭代 n 次,我会这样写:

for (i = 0; i < n; i++) {
    // do stuff
}

在 Python 中,似乎执行此操作的标准方法是:

for x in range(n):
    # do stuff

一如既往,Python 更简洁、更具可读性。但是 x 困扰了我,因为它是不必要的,并且 PyDev 生成警告,因为从未使用过 x 。

有没有一种方法可以做到这一点,不会生成任何警告,并且不会引入不必要的变量?

If I want to iterate n times in Java, I write:

for (i = 0; i < n; i++) {
    // do stuff
}

In Python, it seems the standard way to do this is:

for x in range(n):
    # do stuff

As always, Python is more concise and more readable. But the x bothers me, as it is unnecessary, and PyDev generates a warning, since x is never used.

Is there a way to do this that doesn't generate any warnings, and doesn't introduce unnecessary variables?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

仅一夜美梦 2024-09-22 02:47:22

惯用的 Python(和许多其他语言)会让您使用 _ 作为临时变量,这通常向读者表明该变量是有意未使用的。

除了该约定之外,Python 中的 in 循环结构始终要求您迭代某些内容并将该值分配给变量。

这个问题表明 PyDev 不会为 _ 创建警告)。

for _ in range(n):
    # do stuff

Idiomatic Python (and many other languages) would have you use _ as the temporary variable, which generally indicates to readers that the variable is intentionally unused.

Aside from that convention, the in loop-construct in Python always requires you to iterate over something and assign that value to a variable.

(The comments in the accepted answer of this question suggest that PyDev won't create a warning for _).

for _ in range(n):
    # do stuff
梦旅人picnic 2024-09-22 02:47:22

在 Python 中,您不会在您描述的那种情况下创建额外的变量。

for i in range(10):

创建一个范围对象,循环将在该对象上进行迭代。范围对象在任何给定时间都保留其当前值。 i 只是创建并绑定到该值的名称。

无论变量是否有名称,它都存在,因为范围对象必须知道它的当前值。

如果您从 cpu 指令的角度考虑循环,您就会明白为什么必须有一个变量:

push x
loop:
    do something
    increment x
    jump if x > y
    goto loop

某些 JIT 编译语言中有一种功能,有时会检测到循环只是相同代码的少量重复,并优化代码是一系列相同的指令。但是,据我所知,python 没有做这样的事情。

这是字节码中的 for 循环:

  4           0 SETUP_LOOP              20 (to 23) 
              3 LOAD_GLOBAL              0 (range) 
              6 LOAD_FAST                0 (x) 
              9 CALL_FUNCTION            1 
             12 GET_ITER             
        >>   13 FOR_ITER                 6 (to 22) 
             16 STORE_FAST               1 (i) 

  5          19 JUMP_ABSOLUTE           13 
        >>   22 POP_BLOCK            

请注意,没有比较。迭代对象引发 StopIteration 来退出循环,然后解释器查找循环设置并跳转到循环末尾(在本例中为 23)。

当然,您可以通过重复代码 x 次来避免所有这些。一旦这个数字可能发生变化,就需要某种工具来提供 next() 和 StopIteration 以使 for 循环发挥作用。请记住,Python 的 for 循环与 Java 中的 for-each 循环相当。实际上根本没有可用的传统 for 循环。

顺便说一句:
我总是使用 i、j 和 k 来迭代变量。在我看来,使用下划线似乎不太优雅。

In Python, you don't create an additional variable in the sort of situation you described.

for i in range(10):

Creates a range object, over which the loop iterates. The range object holds it's current value at any given time. i is merely a name that's created and bound to this value.

The variable exists whether it has a name or not, since the range object must know it's current value.

If you think about a loop in terms of cpu instructions, you see why there must be a variable:

push x
loop:
    do something
    increment x
    jump if x > y
    goto loop

There is a facility in some JIT compiled languages that sometimes detects a loop being just a small amount of repetitions of the same code and optimises the code to be a series of the same instructions. But, as far as I know, python does no such thing.

Here's a for-loop in bytecode:

  4           0 SETUP_LOOP              20 (to 23) 
              3 LOAD_GLOBAL              0 (range) 
              6 LOAD_FAST                0 (x) 
              9 CALL_FUNCTION            1 
             12 GET_ITER             
        >>   13 FOR_ITER                 6 (to 22) 
             16 STORE_FAST               1 (i) 

  5          19 JUMP_ABSOLUTE           13 
        >>   22 POP_BLOCK            

Notice that there's no comparison. The loop is quit by the iteration object raising StopIteration, the interpreter then looks up the loop setup and jumps to the end of the loop (23 in this case).

Of course you could avoid all of this by just repeating your code x number of times. As soon as this number may vary, there needs to be some sort of facility to provide next() and StopIteration for the for loop to work.Remember, python's for-loop is if anything comparable to a for-each loop in Java. There really isn't a traditional for-loop available at all.

Just as an aside:
I always use i, j and k for iterating variables. Using the underscore somehow seems inelegant to me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文