是否有我会在 C++ 中执行此操作的 pythonic 首选方法:
for s in str:
if r = regex.match(s):
print r.groups()
我真的很喜欢这种语法,我觉得它比到处都是临时变量要干净得多。唯一不太复杂的其他方法是
for s in str:
r = regex.match(s)
if r:
print r.groups()
我想我是在提示一个相当迂腐的问题。我只是想念以前的语法。
最佳答案
怎么样
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()
关于在 if 语句中重写赋值的 pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3744382/