我正在尝试用清单解决作业。在列表中找到以“ a”开头的第二个元素

时间:2019-09-26 13:23:35

标签: python

到目前为止,这是我的代码:

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

1 个答案:

答案 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

或使用filterenumerate

for (idx, name) in enumerate(filter(lambda x: x.startswith('a'), lst), 1):
    if idx == 2:
        print(name)
        # antonio