【发布时间】:2019-12-12 11:09:07
【问题描述】:
如何将iterable 解压缩到数量不匹配的变量中?
值太多:
>>> one,two = [1,2,3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
可以忽略
>>> one,two,*_ = [1,2,3,4]
>>>
注意:“extended iterable unpacking”仅从 Python 3 开始。关于underscore。
数据太少/变量多的相反情况怎么办:
>>> one,two,three = [1,2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)
>>>
进行处理,特别是为剩余的变量分配None(或其他值)?
类似这样的:
>>> one,two,three = [1,2] or None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)
>>>
https://stackoverflow.com/a/8857846/1619432 建议扩展列表:
>>> one,two,three = [1,2] + [None]*(3-2)
>>> one
1
>>> two
2
>>> three
>>>
【问题讨论】:
-
您是否正在寻找一个更通用的答案,即左侧也可以包含三个以上的变量?
-
@DeveshKumarSingh 是的。不过,数字变量是恒定的。
-
那我觉得不可能实现