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
>>>
追问答案是对的,可是看不懂....
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/203fb80e7bec54e76ed10a42ba389b504fc26aa8?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)
您用的这个是??什么方法.....我是这么写的。。。。结果算等于4.。。。小白的做法。。。。请问怎么改。。。
追答len( # 计算数组元素的数量
[x for x in lst # lst中的每个元素
if x.strip() # 用strip()方法剔除末尾空格、回车后字符串非空
])