Python解压缩中的默认值 [英] Default value in Python unpacking

查看:97
本文介绍了Python解压缩中的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要解压缩的值的数量与变量列表相比太少,是否可以使用默认值?

Is there a way to have a default value if the number of values to unpack is too little compared to the variable list?

例如:

a, b, c = read_json(request)

如果 read_json 返回三个或三个以上变量的数组,则此方法有效。如果只返回两个,则在分配 c 时出现异常。因此,如果无法正确解包,是否可以将 c 设置为默认值?像这样的东西:

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.

谢谢!

推荐答案

您可以尝试 * 进行一些解压缩,处理:

You could try * unpacking with some post-processing:

a, b, *c = read_json(request)
c = c[0] if c else 2

这将分配 a b 正常。如果 c 被分配了某些内容,它将是一个带有一个元素的列表。如果仅解压缩两个值,它将是一个空的列表。第二条语句将第一个元素分配给 c (如果有),否则,默认值为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆