简体   繁体   English

更pythonic的方式来写这个吗?

[英]More pythonic way to write this?

I have this code here: 我在这里有此代码:

import re
def get_attr(str, attr):
    m = re.search(attr + r'=(\w+)', str)
    return None if not m else m.group(1)

str = 'type=greeting hello=world'

print get_attr(str, 'type')   # greeting    
print get_attr(str, 'hello')  # world
print get_attr(str, 'attr')   # None

Which works, but I am not particularly fond of this line: 哪个可行,但我并不特别喜欢这一行:

return None if not m else m.group(1)

In my opinion this would look cleaner if we could use a ternary operator: 我认为,如果我们可以使用三元运算符,这看起来会更干净:

return (m ? m.group(1) : None)

But that of course isn't there. 但是,那当然不存在。 What do you suggest? 你有什么建议?

Python has a ternary operator. Python 具有三元运算符。 You're using it. 您正在使用它。 It's just in the X if Y else Z form. X if Y else Z只是X if Y else Z形式的X if Y else Z

That said, I'm prone to writing these things out. 也就是说,我倾向于将这些内容写出来。 Fitting things on one line isn't so great if you sacrifice clarity. 如果您牺牲了清晰度,那么将事情放在一条线上并不是那么好。

def get_attr(str, attr):
    m = re.search(attr + r'=(\w+)', str)
    if m:
        return m.group(1)

    return None

Another option is to use: 另一种选择是使用:

return m.group(1) if m else m

It's explicit, and you don't have to do any logic puzzles to understand it :) 它是明确的,并且您不必为理解它而做任何逻辑难题:)

return m and m.group(1)

would be one Pythonic way to do it. 这将是一种Python的方式。

If m is None (or something else that evaluates "falsely"), it returns m , but if m is "true-ish", then it returns m.group(1) . 如果mNone (或其他评估为“错误”的东西),则返回m ,但如果m为“ true-ish”,则返回m.group(1)

What you have there is python's conditional operator. 您所拥有的是python的条件运算符。 IMO it's perfectly pythonic as-is and needs no change. IMO完全是pythonic形式,不需要任何更改。 Remember, explicit is better than implicit . 请记住, explicit is better than implicit What you have now is readable and instantly understandable. 您现在拥有的是可读且立即可理解的。

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

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