我具有包含字符串的列表的此函数,并且必须在此列表中找到以“ b”开头的第二个元素。
例如:
second_elemnt_starting_with_b(["b", "a", "bb"]) => "bb"
答案 0 :(得分:7)
使用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'
答案 1 :(得分:1)
尝试一下:
def second_elemnt_starting_with_b(list_):
return [i for i in list_ if i.startswith('b')][1]
print(second_elemnt_starting_with_b(["b", "a", "bb"]))
输出:
'bb'
答案 2 :(得分:0)
lst = ["b", "a", "bb"]
print([i for i in lst if i.startswith("b")][1])
输出:
"bb"
或作为功能:
def func(lst):
return [i for i in lst if i.startswith("b")][1]
答案 3 :(得分:0)
您可以使用python内置函数 startswith()来检查字符串的第一个元素。
lst = ["b", "a", "bb"]
# Check the first element
sample = "Sample"
print(sample.startswith("S"))
# Output : True
现在,您需要遍历列表以检查以 b
开头的每个索引# Create empty list
lst_2 = []
# Loop through list
for element in lst.startswith("b"):
# Add every element starts with b
lst_2.append(element)
# Print the second element which starts with b
print(lst_2[1])