使用Python的过滤功能

lif*_*nce 1 python lambda primes

以下是两个看似等效的函数版本,用于从数字列表中过滤掉素数.

版本1

def prime (mylist):
        for i in range(2, 8):
            return filter(lambda x: x == i or x % i, mylist)
Run Code Online (Sandbox Code Playgroud)

版本2

def prime2 (mylist):
    nums = mylist
    for i in range(2, 8): 
        nums = filter(lambda x: x == i or x % i, nums)
    return nums

print prime([2,3,4,5,6,7,8,9,10,11,12,13,14,15])  
   >> [2, 3, 5, 7, 9, 11, 13, 15]
print prime2([2,3,4,5,6,7,8,9,10,11,12,13,14,15]) 
   >> [2, 3, 5, 7, 11, 13]
Run Code Online (Sandbox Code Playgroud)

版本1返回错误的结果.为什么?

Her*_*utt 6

第一个版本只测试i == 2.换句话说,它只测试2是否是一个因子,而不是按照你的意图测试从2到7的所有整数.这就是为什么它会(正确地)过滤掉所有偶数,但会(错误地)留下不是素数的奇数,如9和15.尝试这样明确地看到它:

def prime (mylist):
    for i in range(2, 8):
        print i # added to make things explicit; it's not necessary
        return filter(lambda x: x == i or x % i, mylist)

def prime2 (mylist):
    nums = mylist
    for i in range(2, 8):
        print i # added to make things explicit; it's not necessary
        nums = filter(lambda x: x == i or x % i, nums)
    return nums

print prime([2,3,4,5,6,7,8,9,10,11,12,13,14,15])
>>> 2
>>> [2, 3, 5, 7, 9, 11, 13, 15]
print prime2([2,3,4,5,6,7,8,9,10,11,12,13,14,15])
>>> 2
>>> 3
>>> 4
>>> 5
>>> 6
>>> 7
>>> [2, 3, 5, 7, 11, 13]
Run Code Online (Sandbox Code Playgroud)