到目前为止,这是我的代码:
def get_second_element_starting_with_a(names):
"""Find the second element in the list which starts with "a"."""
if names != 0 and names != []:
for name in names[1:]:
if name.startswith("a"):
return name
return None
答案 0 :(得分:1)
多种可能的方式:
lst = ['anton', 'berta', 'caesar', 'zacharias', 'antonio']
elements_with_a = [item for item in lst if item.startswith('a')]
if len(elements_with_a) > 1:
print(elements_with_a[1])
# antonio
或-带有索引变量:
lst = ['anton', 'berta', 'caesar', 'zacharias', 'antonio']
def get_second_element_starting_with_a(some_lst):
idx = 0
for name in some_lst:
if name.startswith('a'):
idx += 1
if idx == 2:
return name
return None
print(get_second_element_starting_with_a(lst))
# antonio
或使用filter
和enumerate
:
for (idx, name) in enumerate(filter(lambda x: x.startswith('a'), lst), 1):
if idx == 2:
print(name)
# antonio