我有一个数字[7, 9, 11, 13, 15, 20, 23]
列表,需要从给定列表中创建素数列表。
我已经写了下面的代码,但这也导致9
和15
为素数。我没有得到我在这里想念的东西。
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]
。
答案 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]