Python 非常支持列表解包,但不支持 dict 或对象解包。最令人惊讶和 Pythonic 的方法似乎是手动访问每个项目以构建一个中间元组,如本答案中所述:
a, b = d['a'], d['b']
但是,如果你有很多属性,或者变量名很长,这样做会很麻烦:
great, wow, awesome = dictionary['great'], dictionary['wow'], dictionary['awesome']
对于上下文,上述(解构)的 JavaScript 等价物是:
const {great, wow, awesome} = dictionary;
这是一个更动态的选项:
>>> dictionary = dict(great=0, wow=1, awesome=2)
>>> great, wow, awesome = (dictionary[k] for k in ("great", "wow", "awesome"))
>>> great
0
>>> awesome
2
这仍然很冗长;你可以写一个函数来抽象一些东西,但不幸的是你仍然需要输入两次:
>>> def unpack(dct, *keys):
... return (dct[k] for k in keys)
...
>>> dictionary = dict(great=0, wow=1, awesome=2)
>>> great, wow, awesome = unpack(dictionary, "great", "wow", "awesome")
您也可以将其推广到对象上:
>>> def unpack(x, *keys):
... if isinstance(x, dict):
... return (x[k] for k in keys)
... return (getattr(x, k) for k in keys)
...
>>> from collections import namedtuple
>>> Foo = namedtuple("Foo", "a b c d e")
>>> foo = Foo(a=0, b=1, c=2, d=3, e=4)
>>> c, b, d, a = unpack(foo, "c", "b", "d", "a")
>>> d
3
毕竟,在多行上手动解包可能最适合您需要安全且易于理解的实际生产代码:
>>> great = dictionary["great"]
>>> wow = dictionary["wow"]
>>> awesome = dictionary["awesome"]