增加数组元素的表现力

2024-06-06 19:21:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我喜欢Python的表现力。不过,我不能把每件事都表达得那么紧凑。比如我经常写的这篇文章:

  def is_everything_okay(some_array):
    for s in some_array:
      if not is_okay(s):
        return False
    return True

但这比Python更像Java。如何提高代码片段的表现力(可能还有执行速度)?你知道吗


Tags: infalsetrueforreturnifisdef
2条回答

只需填写斯文的答案*。。。 2.7版文档:http://docs.python.org/library/functions.html#all

all(iterable)
Return True if all elements of the iterable are true (or if the iterable is empty).

Equivalent to:

def all(iterable):
    for element in iterable:
        if not element:
            return False
return True

几乎是你展示的代码的精确副本。。。你知道吗

因此,使用对形式(is_okay(s) for s in some_array)的理解创建了由all()解析的iterable

如果没有具体的测试,你就不知道哪个更快。你知道吗

  • 因为我要结束一个Python课程,所以我需要回答一些问题!你知道吗

使用内置函数^{}

all(is_okay(s) for s in some_array)

相关问题 更多 >