10

考虑这段代码

description = ""
desc = hxs.select('/html/head/meta[2]/@content').extract()
if len(desc) > 0:
    description = desc[0]       
item["description"] = description

desc 是一个字符串列表。如果列表为空,描述为空字符串,否则为列表中的第一个元素。如何让它更pythonic?

忘了说我必须使用 2.7

4

4 回答 4

11

你可以写:

desc = hxs.select("/html/head/meta[2]/@content").extract()
item["description"] = desc[0] if len(desc) > 0 else ""

正如下面评论中所指出的,您还可以直接在布尔上下文中评估列表:

item["description"] = desc[0] if desc else ""
于 2013-07-10T17:50:22.260 回答
10

或者,您可以使用下一个支持默认值的事实

item["description"]  = next(iter(desc), "")
于 2013-07-10T18:07:49.163 回答
1

您可以使用异常处理(尽管它比使用条件表达式更详细)。

desc = hxs.select('/html/head/meta[2]/@content').extract()
try:
    description = desc[0]
except IndexError:
    description = ""
于 2013-07-10T17:59:20.213 回答
0

I don't think you should actually do this in your case, but for completeness…</p>

For an iterator that might be empty, you just use the optional default value for next:

desc = foo.finditer(bar)
item["description"] = next(desc, "")

Meanwhile, you can always use iter() to "peek" at the iterator you would get from a sequence (or other non-iterator iterable).

So:

desc = foo.findall(bar)
item["description"] = next(iter(desc), "")

I think this is less readable than just using the list as a sequence (whether you use chepner's EAFP answer or Frédéric Hamidi's LYBL) rather than just an iterable. After all, we have the sequence API for a reason.

于 2013-07-10T18:11:13.727 回答