簡體   English   中英

JavaScript 的 Array.prototype.some 的 Python 等價物是什么?

[英]What is the python equivalent of JavaScript's Array.prototype.some?

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

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

。NumPy 數組有,但標准 python 列表沒有。 即便如此,numpy 數組實現並不是您所期望的:它們不采用謂詞,而是通過將每個元素轉換為布爾值來評估每個元素。

編輯anyall作為函數(而不是方法)存在,但它們不應用謂詞,而是將布爾值視為 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')

自己試試

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)
  1. list() 接受任何可迭代對象,返回另一個列表:
isEvenList = list(callback(n) for n in numbers)
print(isEvenList)
#[False, True, False, True, False, True, False, True]
  1. any():在布爾值列表中只需要一個 True,返回一個布爾值:
anyEvenNumbers = any( callback(n) for n in numbers)
print(anyEvenNumbers)
#True
  1. all():需要布爾值列表中的所有 True 值,返回一個布爾值:
allEvenNumbers = all( callback(n) for n in numbers)
print(allEvenNumbers)
#False

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM