Skip to main content
 首页 » 编程设计

python之从列表中删除非素数

2025年05月04日8yxwkf

我有这样的东西:

palindromes=[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 101, 111, 121, ..., 99799, 99899, 99999] 
# of course im generating it :) 
 
def isPrime(number): 
    for i in range(2,int(number/2)+1): 
        if number%i == 0: 
            return True 
    return False 
 
def removeNonPrimes(palindromes): 
    for palindrom in palindromes: 
        if isPrime(palindrom): 
            palindromes.remove(palindrom) 
    return palindromes 
 
palindromes = removeNonPrimes(palindromes) 

它不会删除所有非素数

我不明白为什么

请您参考如下方法:

在您的代码中:

def removeNonPrimes(palindromes): 
    for palindrom in palindromes: 
        if isPrime(palindrom): 
            palindromes.remove(palindrom) 
    return palindromes 

您正在修改(使用 .remove())您正在迭代的相同列表(使用 in)。不建议这样做,您最终可能会删除您想要的不同项目。

相反,考虑列表理解:

def removeNonPrimes(palindromes): 
    return [p for p in palindromes if isPrime(p)]