8

I've recently made the following example for Pythons for ... else:

def isPrime(element):
    """ just a helper function! don't get religious about it! """
    if element == 2:
        return True
    elif element <= 1 or element % 2 == 0:
        return False
    else:
        for i in xrange(3, element, 2):
            print i
            if element % i == 0:
                return False
    return True


myList = [4, 4, 9, 12]

for element in myList:
    if isPrime(element):
        break
else:
    print("The list did not contain a prime.")

A fellow student told me, that this task can be done with Scala like this:

List(4, 4, 9, 12) exists isPrime

Which gets lazy evaluated.

Does something similar like the exists-keyword exist in Python? Or is there a PEP for that?

4

2 回答 2

22
myList = [4, 4, 9, 12]

if not any(isPrime(x) for x in myList):
    print("The list did not contain a prime")

Python 也有all()which 曲柄通过任何序列并True在所有元素评估为 true 时返回。

any()并且all()两者都有短路评估:如果any()找到任何评估为真的元素,它就会停止并返回True;如果all()找到任何评估为 false 的元素,它会停止并返回False

两者都很“懒惰”,因为它们使用 Python 迭代一次提取一个值。例如:

import random
def rand_sequence(n_max):
    while True:
        next_random = random.randint(0, n_max)
        print(next_random)
        yield next_random

all(isPrime(x) for x in rand_sequence(20))

这将迭代直到找到一个非素数,然后返回False。它将数字打印为副作用,因此您可以观看它的工作。我刚试过这个并得到:

17
3
0

PS 我参加了一个 Python 会议的演讲,演讲者提到他通常使用any()作为一种非常有效的方式来做一个循环。循环为每个for循环重新绑定循环变量,但any()不这样做;它只是不断检查值。因此,如果您使用any()始终返回None或 false 值的函数,它将一直迭代到序列的末尾,根据那个家伙的说法,这是 Python 中最快的方法。(如果你的函数返回的值不是假的,也不None是假的,你可以使用all()同样的技巧。它唯一不起作用的情况是,有时函数返回一个真值,有时它返回一个假值。但是您可以强制它始终工作:

any(my_function(x) and False for x in sequence)

PPS 让我们用all()重写isPrime()!我将更改名称以is_prime()符合 PEP 8。 http://www.python.org/dev/peps/pep-0008/

def is_prime(element):
    """ just a helper function! don't get religious about it! """
    if element == 2:
        return True
    elif element <= 1 or element % 2 == 0:
        return False
    else:
        return all(element % i for i in xrange(3, element, 2))
于 2012-06-09T06:17:46.810 回答
-1
[x for x in myList if isPrime(x)]
于 2012-06-09T06:19:23.677 回答