use*_*757 3 python list-comprehension list
我正在使用用Python实现的Norvig的BASIC解释器.
有一些代码似乎与我无关,但这个人似乎超出了我的100级,所以我更有可能无法理解而不是写了一些不必要的东西.
def lines(text):
"A list of the non-empty lines in a text."
return [line for line in text.splitlines() if line]
#return [zaa for zaa in text.splitlines()]
Run Code Online (Sandbox Code Playgroud)
列表理解 - 为什么它完成if line?
如果我删除该子句,使用 [zaa for zaa in text.splitlines()]相反,我仍然认为该函数可以工作,如果我传递它文本甚至是一个空行.
foo ="""mike\nnew\nbar"""
bar ="\n\n"
print lines(foo)
print lines(bar)
what = lines(bar)
print(type(what))
['mike', 'new', 'bar']
[]
<type 'list'>
Run Code Online (Sandbox Code Playgroud)
我必须误解某些东西 - 我if line甚至无法理解何时对其进行评估,更不用说正确处理输入的必要性.
编辑:发现缺少的例子if line会给出不好的结果:
bar ="""one
two
three
five
seven"""
#bar = ""
print lines(bar)
['one', 'two', 'three', '', 'five', '', 'seven']
Run Code Online (Sandbox Code Playgroud)
它包含这两个空字符串作为列表的成员.
if line正在检查"truthy"值,这些值是确定的False或True检查时的字符.例如,''考虑空字符串False,以及空列表([]),字典({}),元组(())0和None.基本上,if line是一个较短的版本:
return [line for line in text.splitlines() if line != '']
Run Code Online (Sandbox Code Playgroud)