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

时间:2019-09-02 19:03:21

标签: python python-3.x primes

我有一个数字[7, 9, 11, 13, 15, 20, 23]列表,需要从给定列表中创建素数列表。

我已经写了下面的代码,但这也导致915为素数。我没有得到我在这里想念的东西。

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

我希望输出列表x为[7, 11, 13, 23]

1 个答案:

答案 0 :(得分:5)

如果num % m != 0并不意味着num是质数,则对于所有可能的m值都必须为真(可以通过增加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)

输出:

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