什么是JavaScript的Array.prototype.some的python等价物? [英] What is the python equivalent of JavaScript's Array.prototype.some?

查看:47
本文介绍了什么是JavaScript的Array.prototype.some的python等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python与JavaScript的 Array.prototype等效吗?.some /每个?

Does python have any equivalent to JavaScript's Array.prototype.some / every?

常规JavaScript示例:

Trivial JavaScript example:

var arr = [ "a", "b", "c" ];
arr.some(function (element, index) {
    console.log("index: " + index + ", element: " + element)
    if(element === "b"){
        return true;
    }
});

将输出:

index: 0, element: a
index: 1, element: b

下面的python在功能上似乎是等效的,但我不知道是否有更多的"pythonic"方法.

The below python seems to be functionally equivalent, but I do not know if there is a more "pythonic" approach.

arr = [ "a", "b", "c" ]
for index, element in enumerate(arr):
    print("index: %i, element: %s" % (index, element))
    if element == "b":
        break

推荐答案

Python具有 all(可迭代) any(可迭代).因此,如果您使生成器或迭代器执行所需的功能,则可以使用这些功能对其进行测试.例如:

Python has all(iterable) and any(iterable). So if you make a generator or an iterator that does what you want, you can test it with those functions. For example:

some_is_b = any(x == 'b' for x in ary)
all_are_b = all(x == 'b' for x in ary)

它们实际上是在文档中通过其代码等效项进行定义的.这看起来很熟悉吗?

They are actually defined in the documentation by their code equivalents. Does this look familiar?

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

这篇关于什么是JavaScript的Array.prototype.some的python等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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