[英]python: walrus operator and re.search() in list comprehension
I have a list of strings and I want to extract a pattern from elements.我有一个字符串列表,我想从元素中提取模式。
For instance, given list ["A 12345bcd", "BYT 676 CCC"]
and pattern r'\d\d\d\d\d'
, I would like to obtain: ["12345", ""]例如,给定列表
["A 12345bcd", "BYT 676 CCC"]
和模式r'\d\d\d\d\d'
,我想获得: ["12345", ""]
I know how to do without it, but I want to use walrus operator :=
.我知道没有它怎么办,但我想使用海象运算符
:=
。
I tried:我试过了:
[(m:=re.search(r'\d\d\d\d\d', x), m.group() if m else "") for x in ["A 12345bcd", "BYT 676 CCC"]]
But the result is:但结果是:
[(<re.Match object; span=(2, 7), match='12345'>, '12345'), (None, '')]
Hence, not what I want因此,不是我想要的
This is a tuple:这是一个元组:
(m:=re.search(r'\d\d\d\d\d', x), m.group() if m else "")
This is the group
/empty conditional expression with m:=
evaluated appropriately early:这是带有
m:=
的group
/empty 条件表达式,并在早期得到了适当的评估:
m.group() if (m := re.search(r'\d\d\d\d\d', x)) else ""
import re
l = ["A 12345bcd", "BYT 676 CCC"]
result = [(res := re.search(r"\d{5}", x)) and res.group() or "" for x in l]
print(result)
Output: Output:
['12345', '']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.