Python 相当于 Java 的标准 for 循环是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17415198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:56:36  来源:igfitidea点击:

What is Python's equivalent of Java's standard for-loop?

javapythonloopsfor-looptranslate

提问by Deneb A.

I'm writing a simple algorithm to check the primality of an integer and I'm having a problem translating this Java code into Python:

我正在编写一个简单的算法来检查整数的素数,但在将此 Java 代码转换为 Python 时遇到了问题:

for (int i = 3; i < Math.sqrt(n); i += 2) {
    if (n % i == 0)
        return false;
}

So, I've been trying to use this, but I'm obviously skipping the division by 3:

所以,我一直在尝试使用它,但我显然跳过了 3 的除法:

i = 3
while (i < int(math.sqrt(n))):
    i += 2  # where do I put this?
    if (n % i == 0):
        return False

回答by arshajii

The only for-loop in Python is technically a "for-each", so you can use something like

forPython 中唯一的-loop 在技术上是“for-each”,因此您可以使用类似

for i in xrange(3, int(math.sqrt(n)), 2):  # use 'range' in Python 3
    if n % i == 0:
        return False

Of course, Python can do better than that:

当然,Python 可以做得更好:

all(n % i for i in xrange(3, int(math.sqrt(n)), 2))

would be equivalent as well (assuming there's a return trueat the end of that Java loop). Indeed, the latter would be considered the Pythonicway to approach it.

也将是等效的(假设return true在该 Java 循环的末尾有一个)。事实上,后者将被视为接近它的Pythonic方式。



Reference:

参考:

回答by duskwuff -inactive-

A direct translation would be:

直接翻译是:

for i in range(3, int(math.sqrt(n)), 2):
    if n % i == 0:
        return False

回答by mipadi

In a Java for loop, the step (the i += 2part in your example) occurs at the end of the loop, just before it repeats. Translated to a while, your for loop would be equivalent to:

在 Java for 循环中,步骤(i += 2示例中的部分)发生在循环的末尾,就在它重复之前。转换为一段时间,您的 for 循环将等效于:

int i = 3;
while (i < Math.sqrt(n)) {
    if (n % i == 0) {
        return false;
    }
    i += 2;
}

Which in Python is similar:

这在 Python 中是相似的:

i = 3
while i < math.sqrt(n):
    if n % i == 0:
        return False
    i += 2

However, you can make this more "Pythonic" and easier to read by using Python's xrangefunction, which allows you to specify a stepparameter:

但是,您可以使用 Python 的xrange函数使其更“Pythonic”且更易于阅读,该函数允许您指定step参数:

for i in xrange(3, math.sqrt(n), 2):
    if n % i == 0:
        return False

回答by nanofarad

Use a basic Python for i in rangeloop:

使用基本的 Pythonfor i in range循环:

for i in range(3, math.round(math.sqrt(x)), 2):
    if (n % i == 0):
        return false