如何使用抽象函数在列表中查找某些字符串的位置

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

我试图在列表中找到某些字符串s的位置,但只能使用抽象函数(即filter,map ...)。

find_all([], "") => []
find_all(["a","v","c","w","v"], "v") => [1,4]

我已经尝试过过滤器,但是我不知道如何在其中添加位置。

python
2个回答
0
投票

enumerate与列表理解一起使用:

def find_all(l, k):
    return [i for i,j in enumerate(l) if j == k]

测试:

find_all(["a","v","c","w","v"], "v")
find_all([], "")

输出:

[1, 4]
[]

0
投票

也许是这样?

[item[0] for item in list(filter(lambda x : x[1] == 'v',enumerate(x)))]

输出:

[1, 4]

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