Python 在匹配空行时,如何获取字符串列表并对其进行计数?
像这样的东西Python 在匹配空行时,如何获取字符串列表并对其进行计数?,python,string,list,function,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'
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
"""
将告诉您字符串是否都是空白字符。因此,您可以使用sum
并计算lst
中有多少项返回True
用于非item.isspace()
:
def count_lines(lst):
return sum(1 for line in lst if line.strip())
>>> 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
>>>