简体   繁体   English

有什么办法可以压缩Python中的for-else循环吗?

[英]Is there any way to condense a for-else loop in Python?

I have made a piece of code that spits out prime numbers up to the 10001st number. 我编写了一段代码,最多输出10001st个质数。 It currently takes up 4 lines of code, and was wondering if I could condense it further? 它目前占用4行代码,并且想知道我是否可以进一步压缩它? Here it is; 这里是;

for i in range(3,104744,2):
    for x in range(3,int(i/2),2):
        if i % x == 0 and i != x: break
    else: print(i)

I am aware that condensing code too much is usually not a good thing, but was wondering if it was possible. 所知,冷凝代码太多,通常不是一件好事,但不知道是否有可能。

Thanks. 谢谢。

You can use a list comprehension and any to get a one-liner solution: 您可以使用列表推导和any列表推导解决方案:

>>> [p for p in range(2, 100) if not any (p % d == 0 for d in range(2, int(p**0.5) + 1))]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

It uses the fact that a divisor cannot be larger than the square root of the number it divies. 它使用除数不能大于其除数的平方根的事实。

It seems to work fine: 似乎工作正常:

>>> len([p for p in range(2, 104744) if not any (p % d == 0 for d in range(2,int(p**0.5)+1))])
10001

List comprehension 清单理解

>>> r=range(2,100)
>>> [p for p in r if [p%d for d in r].count(0)<2]

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] [2、3、5、7、11、13、17、19、23、29、31、37、41、43、47、53、59、61、67、71、73、79、83、89、97 ]

Try this one: 试试这个:

for i in range(3,100,2):
    if all( i%x for x in range(3, i//2, 2) ):
        print(i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM