pythonic方法在if语句中重写赋值 [英] pythonic way to rewrite an assignment in an if statement
本文介绍了pythonic方法在if语句中重写赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有一种pythonic首选的方法来做我在C ++中做的事情:
Is there a pythonic preferred way to do this that I would do in C++:
for s in str:
if r = regex.match(s):
print r.groups()
我非常喜欢这种语法,因为它比在任何地方都有临时变量要清晰得多。另一种不太复杂的方式是
I really like that syntax, imo it's a lot cleaner than having temporary variables everywhere. The only other way that's not overly complex is
for s in str:
r = regex.match(s)
if r:
print r.groups()
I猜猜我在抱怨一个非常迂腐的问题。我只是错过了以前的语法。
I guess I'm complaining about a pretty pedantic issue. I just miss the former syntax.
推荐答案
怎么样
for r in [regex.match(s) for s in str]:
if r:
print r.groups()
或更多功能
for r in filter(None, map(regex.match, str)):
print r.groups()
这篇关于pythonic方法在if语句中重写赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文