[英]Can I assign value to a variable among if condition on Python
I write my code that way, I want to assign matched values to 'm' but lst[1] may not including the pat I want. 我以这种方式编写代码,我想将匹配的值分配给'm',但是lst [1]可能不包括我想要的pat。 if it does, so I'll keep do something about 'm' eg: m.group(2).split() ....
如果确实如此,那么我会继续做一些关于'm'的事情,例如:m.group(2).split()....
if re.match(pat, lst[1]):
m=re.match(pat, lst[1])
But I don't want to repeat the re.match(pat, lst[1]) twice. 但我不想重复两次re.match(pat,lst [1])。
I want to achieve in that way 我希望以这种方式实现
if m = re.match(pat, lst[i])
but it shows me "invalid syntax error. any ideas? 但它告诉我“语法错误无效。任何想法?
Just assign the value beforehand and check if it's None: 只需预先指定值并检查它是否为None:
m = re.match(pat,lst[1])
if not m:
del m
You can abuse for
for your task. 你可以滥用
for
您的任务。
def for_if(expression):
if expression:
yield expression
for m in for_if(re.match(pat, lst[1])):
# work with m
or just 要不就
for m in (i for i in (re.match(pat, lst[1]),) if i):
# do the same
This is not really helpful for readability, but is the only way to combine assignment and test. 这对可读性并没有多大帮助,但却是将赋值和测试结合起来的唯一方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.