Python 根据函数求值查找列表中元素的索引

问题描述 投票:0回答:1

我试图根据 lambda 函数(或其他可调用函数)的评估值查找 Python 列表中项目的索引。

这类似于

.index()
操作与
find_if
操作的组合。

这是一个例子:

# self contains `self.list`
def find_index_where(self, id: int) -> int:

    # callable expression which tests a sub-member of some object `input`
    def lambda_callable(input, id):
        return input.id == id

    # extra work being done:
    # first find an `item` then find an `index` corresponding to `item`
    matched_item = next(item for item in self.list if lambda_callable(item, id))
    index = self.list.index(matched_item)
    return index

有没有办法将“项目查找”操作与“索引查找”操作一起滚动?

python
1个回答
0
投票

你可以使用这个:

def find_index_where(self, id: int) -> int:
    def lambda_callable(input, id):
        return input.id == id
    try:
        index = next(index for index, item in enumerate(self.list) if lambda_callable(item, id))
    except StopIteration:
        raise ValueError("Item not found in the list.")

    return index
© www.soinside.com 2019 - 2024. All rights reserved.