Python 打印 1-99 奇数的最有效代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21793424/
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-08-18 23:38:30  来源:igfitidea点击:

most efficient code for printing odd numbers from 1-99

python

提问by neenertronics

The task is to print the odd numbers from 1-99 on separate lines.

任务是在不同的行上打印 1-99 的奇数。

Codeeval deemed this code partially correct (98 out of 100): (edited)

Codeeval 认为此代码部分正确(100 个中有 98 个):(已编辑)

liszt = (i for i in range(1,100) if i%2!=0)
for i in liszt:
    print i

Codeeval deemed the below code completely correct:

Codeeval 认为以下代码完全正确:

liszt = range(1,100)
for i in liszt:
    if i%2!=0:
        print i

New to Python, so just looking to understand why one method might be considered better than the other. Is the second method more efficient?

Python 新手,所以只是想了解为什么一种方法可能被认为比另一种更好。第二种方法更有效吗?

Thanks for the help!

谢谢您的帮助!

采纳答案by Ankur Ankan

In the first code you are iterating over two generators first range(1, 100)and then over lisztwhereas in the second case the iteration is only over liszt. Other than that the operation is same in both the cases, so the second method is more efficient.

在第一个代码中,您首先迭代两个生成器range(1, 100),然后再迭代,liszt而在第二种情况下,迭代仅结束liszt。除此之外,两种情况下的操作相同,因此第二种方法更有效。

Since every second number after 1 would be odd, a better solution could be:

由于 1 之后的每个第二个数字都是奇数,因此更好的解决方案可能是:

for i in range(1, 100, 2):
    print(i)

回答by Hugh Bothwell

print("\n".join(str(i) for i in range(1,100,2)))