python是否与JavaScript Array.prototype.some / every等效?
简单的JavaScript示例:
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"方法
arr = [ "a", "b", "c" ]
for index, element in enumerate(arr):
print("index: %i, element: %s" % (index, element))
if element == "b":
break
答案 0 :(得分:14)
Python有all(iterable)
和any(iterable)
。因此,如果您创建一个可以执行所需操作的生成器或迭代器,则可以使用这些函数对其进行测试。例如:
some_is_b = any(x == 'b' for x in ary)
all_are_b = all(x == 'b' for x in ary)
它们实际上是通过它们的代码等价物在文档中定义的。这看起来很熟悉吗?
def any(iterable):
for element in iterable:
if element:
return True
return False
答案 1 :(得分:0)
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
def callback( n ):
return (n % 2 == 0)
# 1) Demonstrates how list() works with an iterable
isEvenList = list( callback(n) for n in numbers)
print(isEvenList)
# 2) Demonstrates how any() works with an iterable
anyEvenNumbers = any( callback(n) for n in numbers)
print(anyEvenNumbers)
# 3) Demonstrates how all() works with an iterable
allEvenNumbers = all( callback(n) for n in numbers)
print(allEvenNumbers)
isEvenList = list(callback(n) for n in numbers)
print(isEvenList)
#[False, True, False, True, False, True, False, True]
anyEvenNumbers = any( callback(n) for n in numbers)
print(anyEvenNumbers)
#True
allEvenNumbers = all( callback(n) for n in numbers)
print(allEvenNumbers)
#False
答案 2 :(得分:-1)
没有。 NumPy arrays have,但标准的python列表没有。即便如此,numpy数组实现并不是你所期望的:它们不接受谓词,而是通过将每个元素转换为布尔值来评估每个元素。
编辑:any
和all
作为函数(而非方法)存在,但它们不应用谓词,但将布尔值视为numpy方法。
在Python中,some
可以是:
def some(list_, pred):
return bool([i for i in list_ if pred(i)])
#or a more efficient approach, which doesn't build a new list
def some(list_, pred):
return any(pred(i) for i in list_) #booleanize the values, and pass them to any
您可以实施every
:
def every(list_, pred):
return all(pred(i) for i in list_)
修改:哑样本:
every(['a', 'b', 'c'], lambda e: e == 'b')
some(['a', 'b', 'c'], lambda e: e == 'b')
自己尝试