如何在忽略空行的同时获取字符串列表并计算它们?

时间:2014-11-16 19:10:03

标签: python string list function

def count_lines(lst):
    """ (list of str) -> int

    Precondition: each str in lst[:-1] ends in \n.

    Return the number of non-blank, non-empty strings in lst.

    >>> count_lines(['The first line leads off,\n', '\n', '  \n',
    ... 'With a gap before the next.\n', 'Then the poem ends.\n'])
    3
    """

2 个答案:

答案 0 :(得分:1)

像这样;

def count_lines(lst):
   return sum(1 for line in lst if line.strip())

答案 1 :(得分:1)

str.isspace会告诉您字符串是否都是空白字符。因此,您可以使用sum并计算lstTrue返回not item.isspace()的项目数:

>>> def count_lines(lst):
...     return sum(not x.isspace() for x in lst)
...
>>> count_lines(['The first line leads off,\n', '\n', '  \n', 'With a gap before the next.\n', 'Then the poem ends.\n'])
3
>>>