0

我想定义 N 个具有不同 int 值的变量(作为状态标记,所以唯一的要求是每个 var 的值不同)。起初我有:

state_default, state_open, state_close = range(3)

然后过了一段时间,要添加新的状态变量,我会将其更改为下面的代码

state_default, state_open, state_close, state_error = range(4)

不知何故,我经常忘记将 range(3) 更改为 range(4),因此会引发关于解包的异常。

我知道在python3中,可以这样处理:

state_default, state_open, state_close, *placeholder = range(1000)

所以我想知道python2中是否有一个解决方案,我可以无限次(或者只是很多次)解压一个对象

总之我希望它可以通过下面的测试

a,b,c = InfiniteUnpackableObject()  # shouldn't give me unpacking error
a,b,c,d = InfiniteUnpackableObject()  # shouldn't give me unpacking error either
4

1 回答 1

0
>>> it = iter(range(4))
>>> a = next(it)
>>> b = next(it)
>>> c = next(it)
>>> d = list(it)
>>> a
0
>>> b
1
>>> c
2
>>> d
[3]

更一般地,作为生成器:

def unpack_collect(iterable, n):
    """Yields the first n values of an interable, and returns the rest as a list."""
    it = iter(iterable)
    for _ in range(n):
        yield next(it)
    yield list(it)

并在使用中:

>>> a, b, c, d = unpack_collect('qwerty', 3))
>>> (a, b, c, d)
('q', 'w', 'e', ['r', 't', 'y'])
于 2019-02-28T06:06:20.200 回答