安全解包空元组数组 [英] Safe unpack empty tuple array
问题描述
行 import re;print(re.findall("(.*) (.*)", "john smith"))
输出[("john", "smith")]
,可以是像 [(first_name, last_name)] = re.findall(...)
一样解压.但是,如果出现不匹配(findall
返回 []
),则此解包会引发 ValueError: not enough values to unpack (expected 1, got 0)代码>.
The line import re; print(re.findall("(.*) (.*)", "john smith"))
outputs [("john", "smith")]
, which can be unpacked like [(first_name, last_name)] = re.findall(...)
. However, in the event of a non-match (findall
returning []
) this unpacking throws ValueError: not enough values to unpack (expected 1, got 0)
.
安全解包这个元组数组的正确方法是什么,它可以在匹配 ([("john", "smith")]
) 和不匹配 ([]
) 场景?
What is the correct way to safely unpack this array of tuples, which would work in both match ([("john", "smith")]
) and non-match ([]
) scenarios?
推荐答案
一般的答案是在你飞跃之前先看看:
The generic answer is to look before you leap:
if result:
[(first_name, last_name)] = result
或请求原谅:
try:
[(first_name, last_name)] = result
except ValueError:
pass
但是您实际上通过使用 re.findall()
来查找单个结果使事情变得过于复杂.使用 re.seach()
并提取您的匹配组:
but you are actually overcomplicating things by using re.findall()
to find a single result. Use re.seach()
and extract your matched groups:
match = re.search("(.*) (.*)", value)
if match:
firstname, lastname = match.groups()
或
try:
firstname, lastname = re.search("(.*) (.*)", value).groups()
except AttributeError:
# An attribute error is raised when `re.search()` returned None
pass
这篇关于安全解包空元组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!