Python解包中的默认值 [英] Default value in Python unpacking
问题描述
如果与变量列表相比,要解包的值的数量太少,有没有办法获得默认值?
例如:
a, b, c = read_json(request)
如果 read_json
返回三个或更多变量的数组,则此方法有效.如果它只返回两个,我会在分配 c
时遇到异常.那么,如果不能正确解包,有没有办法将 c
设置为默认值?类似的东西:
a, b, (c=2) = read_json(request)
这与定义带有默认参数的函数时所做的类似.
谢谢!
你可以试试 *
解包一些后处理:
a, b, *c = read_json(request)c = c[0] 如果 c 否则 2
这将正常分配 a
和 b
.如果 c
被赋值,它将是一个带有一个元素的 list
.如果只解压了两个值,它将是一个空的 list
.如果存在,则第二条语句将其第一个元素分配给 c
,否则为 2
的默认值.
Is there a way to have a default value if the number of values to unpack is too little compared to the variable list?
For example:
a, b, c = read_json(request)
This works if read_json
returns an array of three or more variable. If it only returns two, I get an exception while assigning c
. So, is there a way to set c
to a default value if it can't be unpacked properly? Something like:
a, b, (c=2) = read_json(request)
Which is similar to what you do when defining a function with default arguments.
Thank you!
You could try *
unpacking with some post-processing:
a, b, *c = read_json(request)
c = c[0] if c else 2
This will assign a
and b
as normal. If c
is assigned something, it will be a list
with one element. If only two values were unpacked, it will be an empty list
. The second statement assigns to c
its first element if there is one, or the default value of 2
otherwise.
>>> a, b, *c = 1, 2, 3
>>> c = c[0] if c else 2
>>> a
1
>>> b
2
>>> c
3
>>> a, b, *c = 1, 2
>>> c = c[0] if c else 2
>>> a
1
>>> b
2
>>> c
2
这篇关于Python解包中的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!