1

我正在对两个条件ProfileBuildDate. 我想说明我会找到两个、一个或没有结果并返回尽可能多的信息的可能性。这是我的编写方式,但我想知道是否有更 Pythonic 的方式?

    p = re.search(r'Profile\t+(\w+)',s)
    d = re.search(r'BuildDate\t+([A-z0-9-]+)',s)

    # Return whatever you can find. 
    if p is None and d is None:
        return (None, None)
    elif p is None:
        return (None, d.group(1))
    elif d is None:
        return (p.group(1), None)
    else:
        return (p.group(1),d.group(1))
4

1 回答 1

3
p = re.search(r'Profile\t+(\w+)',s)
d = re.search(r'BuildDate\t+([A-z0-9-]+)',s)

return (p.group(1) if p is not None else None,
        d.group(1) if d is not None else None)

也是这样:

return (p and p.group(1), d and d.group(1))

这不那么冗长,但有点模糊。

于 2013-02-22T17:55:45.653 回答