简体   繁体   English

Pythonic方式写两个if语句

[英]Pythonic way to write two if-statements

I have two variables that are the result of regex searches. 我有两个变量是正则表达式搜索的结果。

a = re.search('some regex', str)
b = re.search('different regex', str)

This should return a re object. 这应该返回一个re对象。 If they are not None, I want to use the group() method to get the string that it matched. 如果它们不是None,我想使用group()方法获取它匹配的字符串。 This is the code I am using right now to do this: 这是我现在使用的代码:

if a != None:
   a = a.group()
if b != None:
   b = b.group()

Is there a more clever way to write these two if-statements? 是否有更聪明的方法来编写这两个if语句? Maybe combine them into one? 也许将它们组合成一个? I think taking up 4 lines to do this is too verbose. 我认为用4行来做这件事太冗长了。

Thanks. 谢谢。

Don't shadow the built-in str , and say 不要遮住内置的str ,然后说

if a:

instead of 代替

if a != None

Not much else to improve imho. 没有什么可以改善imho。

a = a.group() if a else None

如果你真的必须有一个单行:

a, b = a.group() if a else None, b.group() if b else None

As I commented, I prefer not to reuse a and b for both the Match object and the matched text. 正如我评论的那样,我不想为Match对象和匹配的文本重用ab I'd go with a function to pull out the match, like this: 我会选择一个函数来取出匹配,如下所示:

>>> def text_or_none(v): return v.group() if v is not None else None
>>> a = text_or_none(re.search("\d", "foo"))
None
>>> b = text_or_none(re.search("\w+", "foo"))
foo

You can refactor little: 你可以重构一点:

a, b = (var.group() if var is not None else None for var in (a,b) )

This keeps value of a if it is for example 0. This is the end of your request. 如果它是例如0,则保持a的值。这是您的请求的结束。

However after some time passed I came up with this suggestion considering context: 但是经过一段时间后,我想到了这个建议:

import re
target = """"Id","File","Easting","Northing","Alt","Omega","Phi","Kappa","Photo","Roll","Line","Roll_line","Orient","Camera"
1800,2008308_017_079.tif,530658.110,5005704.180,2031.100000,0.351440,-0.053710,0.086470,79,2008308,17,308_17,rightX,Jen73900229d
"""
print target
regs=(',(.*.tif)',',(left.*)',',(right.*)')
re_results=(result.group()
            for result in ((re.search(reg, target)
                            for reg in regs)
                           )
            if result is not None)
print list(re_results)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM