从列表中删除非质数 [英] Removing non-primes numbers from list

查看:106
本文介绍了从列表中删除非质数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的事情:

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)

并且它不会删除所有非素数

And it doesnt remove all non primes

我不知道为什么

推荐答案

在您的代码中:

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

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

You are modifying (with .remove()) the same list you're iterating over (with in). This is not recommended and you may end up removing different items that you intend.

相反,考虑一个列表推导:

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

这篇关于从列表中删除非质数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆