Skip to main content
 首页 » 编程设计

python之如何返回列表中以 "b"开头的第二个元素

2025年05月04日14sharpest

我有这个函数,列表中有字符串,我必须找到这个列表中以“b”开头的第二个元素。

例如:

second_elemnt_starting_with_b(["b", "a", "bb"]) => "bb" 

请您参考如下方法:

使用 generator 会更有效率,而不是通过遍历整个初始列表来构建所有以 'b' 开头的字符串的列表,然后只保留第二个。

def second_element_starting_with_b(lst): 
    # g is a generator, it will produce items lazily when we call 'next' on it  
    g = (item for item in lst if item.startswith('b')) 
    next(g)  # skip the first one 
    return next(g) 
 
 
 
second_element_starting_with_b(["b", "a", "bb"])  
# 'bb' 

这样,一旦找到我们要查找的字符串,代码就会停止在初始列表上迭代。

正如@Chris_Rands 所建议的,也可以通过使用 itertools.islice 来避免重复调用 next .这样,查找以“b”开头的第 n 个项目的扩展版本将如下所示:

from itertools import islice 
 
def nth_element_starting_with_b(lst, n): 
    "Return nth item of lst starting with 'b', n=1 for first item" 
    g = (item for item in lst if item.startswith('b')) 
    return next(islice(g, n-1, n)) 
 
 
 
nth_element_starting_with_b(["b", "a", "bb"], 2)  
# 'bb'