python - 在列表理解中使用 'if'

标签 python list list-comprehension

我正在处理 Norvig's BASIC interpreter implemented in Python .

有一些代码我觉得很无关紧要,但是这个人似乎比我高了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()]

列表理解 -- 为什么它以 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'>

我一定是误解了什么——我什至无法理解 if 行 何时被评估,更不用说它在正确处理输入方面的必要性了。

编辑:找到缺少 if 行 会产生不良结果的示例:

bar ="""one
two
three

five

seven"""
#bar = ""
print lines(bar)

['one', 'two', 'three', '', 'five', '', 'seven']

它将这两个空字符串作为列表的成员。

最佳答案

if line正在检查“真实”值,这些值是确定的字符 FalseTrue检查时。例如,空字符串 ''被认为是False ,以及空列表 ( [] )、字典 ( {} )、元组 ( () )、0 , 和 None .本质上,if line是一个较短的版本:

return [line for line in text.splitlines() if line != '']

关于python - 在列表理解中使用 'if',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47575837/

相关文章:

python - PIL.Image.fromarray 在 np.reshape 之后产生扭曲的图像

python - 如何在 Python 中仅将字符串的特定部分转换为大写?

python - 将带有坐标的一维数组转换为numpy中的二维数组

Python 属性最佳实践,属性内的函数

list - Dart可观察 list 已移除项目

python - 如何将空格和逗号分隔的数字字符串转换为 int 列表?

list - 返回和的 Lisp 函数

python - Python 中 2 的幂的列表理解因 numpy 数组而失败

python - 在列表理解python中的每个元素后插入逗号

python - 列表理解条件中的 `elif`