python list comprehensions - ['False']没有打印

时间:2015-09-24 01:33:43

标签: python

有没有人知道为什么我不能从这里打印assignment(1, 67).

False

或在这里

print [e.text if "Born" in r.text() else 'False' for e in r.nextAll("td span .bday")]

一切正常,除了print ['False' if "Born" not in r.text() else e.text for e in r.nextAll("td span .bday")] 我没有空括号['False']

2 个答案:

答案 0 :(得分:1)

您将获得空括号,因为r.nextAll()返回一个空迭代器。把它分解成简单的东西。例如:

>>> print ['foo' if False else 'bar' for e in []]
[]
>>> print ['foo' if False else 'bar' for e in [2]]
['bar']
>>> print ['foo' if False else 'bar' for e in [2, 3]]
['bar', 'bar']
>>> print ['foo' if not False else 'bar' for e in []]
[]
>>> print ['foo' if not False else 'bar' for e in [2]]
['foo']
>>> print ['foo' if not False else 'bar' for e in [2, 3]]
['foo', 'foo']
>

如果您不相信这一点,请尝试打印list(r.nextAll("td span .bday"))

答案 1 :(得分:0)

叶氏!问题出在list(r.nextAll("td span .bday")),返回空[]

我解决了这个问题:

lambda r: [e.text for e in r.nextAll("td span .bday")] or ['False']

谢谢!