python解包零元素

2024-03-28 08:22:48 发布

您现在位置:Python中文网/ 问答频道 /正文

请考虑以下代码段:

# state that items contains two or more elements
x, y, *_ = items

# state that items contains exactly two elements
x, y, = items

# state that items contains exactly one element
x, = items

我能以类似的方式声明items包含零个元素吗?你知道吗

提前谢谢!你知道吗


Tags: or声明元素thatmore代码段方式items
2条回答

您可以使用:

() = items

如果items的元素数超过0,则ValueError将引发。你知道吗

这在Python 3.6中有效:

>>> items = []
>>> () = items
>>> items = [1,2]
>>> () = items
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 0)

不是以类似的方式,但是您可以尝试访问iterable的第一项。如果引发异常,iterable为空。这种方法被称为EAFP方式(更容易请求原谅而不是允许。)。或者,如果iterable为空,则可以通过检查布尔值来检查iterable是否为空。话虽如此,对于迭代器可以使用next()方法,对于iterables可以使用索引(__getitem__)等

# Easier to ask for forgiveness than permission.
In [41]: try:
    ...:     item[0]
    ...: except:
    ...:     print("empty list")
empty list

#或

In [45]: items = iter([])

In [46]: try:
    ...:     next(items)
    ...: except StopIteration:
    ...:     print("empty list")
    ...:     
empty list

相关问题 更多 >