简体   繁体   English

如何从给定列表创建素数列表?

[英]How to create a list of prime numbers from a given list?

I have a list of numbers [7, 9, 11, 13, 15, 20, 23] and I need to create a list of Prime numbers from given list. 我有一个数字列表[7, 9, 11, 13, 15, 20, 23] ,我需要根据给定列表创建一个素数列表。

I have written below code but this results 9 & 15 as prime too. 我已经写了下面的代码,但这也导致915为素数。 I am not getting what I am missing here. 我没有得到我在这里想念的东西。

a = [7, 9, 11, 13, 15, 20, 23] 

x = []
for i in range (0, len(a)):
    num = a[i]
    for m in range (2,num):
        if (num % m)==0:
            break
        else:
            print('This is prime', num)
            x.insert(i, num)
            break

I Expect the output list x as [7, 11, 13, 23] . 我期望输出列表x为[7, 11, 13, 23]

If num % m != 0 doesn't mean that num is prime, it must be true for all possible m values (which can be reduced by going up to num // 2 , and can even be reduced to go up to just sqrt(num) ), for that, you can use a for ... else block (the else block will execute only when the for exits normally, without a break , which only happens with prime numbers): 如果num % m != 0并不意味着num是素数,则它对于所有可能的m值都必须为true(可以通过增加到num // 2来减少,甚至可以减少到仅仅sqrt(num) ),为此,您可以使用for ... else块( else块将仅在for正常退出时执行,而不会出现break ,这仅发生在质数上):

a = [7, 9, 11, 13, 15, 20, 23] 

x = []
for num in a:   #   iterate with the value when you don't need the index
    for m in range(2, (num // 2) + 1):
        if num % m == 0:
            break
    else:
        print('This is prime', num)
        x.append(num)   #   use `append` to insert at the tail of the list

print(x)

Output: 输出:

This is prime 7
This is prime 11
This is prime 13
This is prime 23
[7, 11, 13, 23]

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

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