Python赋值破坏

2024-04-29 07:00:22 发布

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

如何在Python中进行ES6类型的对象分解?在

dictionary = {}

dictionary['a'] = 'hello'
dictionary['b'] = 'goodbye'

print dictionary

a, b = [dictionary]

print a, b

我怎样才能让它打印hello goodbye?在


Tags: 对象类型hellodictionaryprintes6goodbye
3条回答

您可以通过exec()来模拟对象的解构。在

[exec("global %s; %s=%s" % (var,var,repr(val))) 
              for var,val in dictionary.items() if var.isidentifier()]

print(a)
#hello

为了方便起见,您可以编写一个函数来隐藏所有技术细节:

^{pr2}$

您应该通过dictionary的键提取它们的设置值:

dictionary = {}

dictionary['a'] = 'hello'
dictionary['b'] = 'goodbye'

print dictionary

a, b = dictionary['a'], dictionary['b']

print a, b

字典不保留键和值的顺序。这意味着,如果您需要字典中键或值的有序结果,您应该记住这一点。在

你可以这样做:

a, b = dictionary.values()

或者,如果您担心字典没有订购,您可以:

^{pr2}$

相关问题 更多 >