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?
但那当然不存在。你有什么建议?
4 个解决方案
#1
10
Python has a ternary operator. You're using it. It's just in the X if Y else Z
form.
Python有一个三元运算符。你正在使用它。它只是在X中,如果是其他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
#2
4
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 :)
它是明确的,你不必做任何逻辑谜题来理解它:)
#3
3
return m and m.group(1)
would be one Pythonic way to do it.
将是一种Pythonic方式来做到这一点。
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)
.
如果m是None(或其他评估“falsely”的东西),则返回m,但如果m是“true-ish”,则返回m.group(1)。
#4
2
What you have there is python's conditional operator. IMO it's perfectly pythonic as-is and needs no change. Remember, explicit is better than implicit
. What you have now is readable and instantly understandable.
你有什么是python的条件运算符。 IMO它完全是pythonic as-is,不需要改变。请记住,显式优于隐式。你现在拥有的是可读的,可以立即理解的。
#1
10
Python has a ternary operator. You're using it. It's just in the X if Y else Z
form.
Python有一个三元运算符。你正在使用它。它只是在X中,如果是其他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
#2
4
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 :)
它是明确的,你不必做任何逻辑谜题来理解它:)
#3
3
return m and m.group(1)
would be one Pythonic way to do it.
将是一种Pythonic方式来做到这一点。
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)
.
如果m是None(或其他评估“falsely”的东西),则返回m,但如果m是“true-ish”,则返回m.group(1)。
#4
2
What you have there is python's conditional operator. IMO it's perfectly pythonic as-is and needs no change. Remember, explicit is better than implicit
. What you have now is readable and instantly understandable.
你有什么是python的条件运算符。 IMO它完全是pythonic as-is,不需要改变。请记住,显式优于隐式。你现在拥有的是可读的,可以立即理解的。