如何打印列表中包含起始字母“A”的元素

时间:2016-08-22 08:26:36

标签: python python-3.x

我想在列表中打印一个包含100多个名字的元素。在这100个名字中我只想打印起始字母'A'的名字。我怎么能在python中这样做?

1 个答案:

答案 0 :(得分:0)

您可以使用列表理解:

>>> my_list = ['apple', 'Alexander', 'Ball', 'Alphabet']
>>> a_list = [element for element in my_list if element.startswith('A')]
>>> a_list
['Alexander', 'Alphabet']

或者,更多Pythonic的方法是使用itertools.ifilter()

>>> import itertools
>>> my_list = ['apple', 'Alexander', 'Ball', 'Alphabet']
>>> list(itertools.ifilter(lambda x: x.startswith('A'), my_list))
['Alexander', 'Alphabet']