使用列表理解查找素数 [英] Finding prime numbers using list comprehention

查看:61
本文介绍了使用列表理解查找素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图生成x到y范围内的所有素数.我首先尝试了一个简单的示例:range(10,11),这意味着检查10是否为质数:
这是我的代码:

I was trying to generate all prime numbers in range x to y. I tried simple example first: range(10,11) which means to check if 10 is a prime number:
Here is my code:

prime_list = [x for x in range(10, 11) for y in range(2,x) if x % x == 0 and x % 1 == 0 and x % y != 0]

我知道这个东西缺少告诉表达式x%y != 0应该对range (2,x)中的所有y进行检查的选项,并且仅当所有条件都满足此条件时才返回true.

I know that the thing is missing the option to tell the expression that x%y != 0 should be checked for all y in range (2,x) and return true if and only if all have met this condition.

我们该怎么做?

推荐答案

使用 all 检查所有元素(从2到x-1)是否满足条件:

Use all to check all elements (from 2 upto x-1) met conditions:

>>> [x for x in range(2, 20)
     if all(x % y != 0 for y in range(2, x))]
[2, 3, 5, 7, 11, 13, 17, 19]

这篇关于使用列表理解查找素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆