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
"""
答案 0 :(得分:1)
像这样;
def count_lines(lst):
return sum(1 for line in lst if line.strip())
答案 1 :(得分:1)
str.isspace
会告诉您字符串是否都是空白字符。因此,您可以使用sum
并计算lst
中True
返回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
>>>