我正在使用代码查找主要因素,但是for循环永远不会启动65。为什么?
import math
sq = int(math.sqrt(13195))
lis = []
for x in range(2,sq):
if 13195 % x == 0:
lis.append(x)
for y in lis:
print(y)
for z in range(2,y):
if y % z == 0:
print(y,"is not a prime")
if y in lis:
lis.remove(y)
else:
continue
print(lis)
我希望输出为[5,7,13,29]
,但实际输出为[5,7,13,29,65]
答案 0 :(得分:2)
您要在迭代同一列表时删除元素,请使用切片或副本对其进行求解:
for y in lis[::]: # make a copy of the original list to avoid the problem
print(y)
for z in range(2,y):
if y % z == 0:
print(y,"is not a prime")
if y in lis:
lis.remove(y)
else:
continue