python计算list中非空str的数量 求function body!!

def count_lines(lst):
r""" (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
"""

Python 2.7.3 (default, Mar 14 2014, 11:57:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def count_lines(lst):
...     r""" (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
...     """
...     return len([x for x in lst if x.strip()])
... 
>>> 
>>> count_lines(['The first line leads off,\n', '\n', '  \n',
...     'With a gap before the next.\n', 'Then the poem ends.\n'])
3
>>>

追问

    答案是对的,可是看不懂....

    您用的这个是??什么方法.....我是这么写的。。。。结果算等于4.。。。小白的做法。。。。请问怎么改。。。
追答len(  # 计算数组元素的数量
    [x for x in lst  # lst中的每个元素 
     if x.strip()    # 用strip()方法剔除末尾空格、回车后字符串非空
     ])

温馨提示:答案为网友推荐,仅供参考
相似回答