一次将Python字典的内容分配给多个变量吗? [英] Assign contents of Python dict to multiple variables at once?
本文介绍了一次将Python字典的内容分配给多个变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做这样的事情
def f():
return { 'a' : 1, 'b' : 2, 'c' : 3 }
{ a, b } = f() # or { 'a', 'b' } = f() ?
即这样a被分配为1,b得到2,而c是未定义的
I.e. so that a gets assigned 1, b gets 2, and c is undefined
这类似于
def f()
return( 1,2 )
a,b = f()
推荐答案
对于依赖于变量名的解包没有任何意义。您可以得到的最接近值是:
It wouldn't make any sense for unpacking to depend on the variable names. The closest you can get is:
a, b = [f()[k] for k in ('a', 'b')]
当然,这将评估 f()
两次。
您可以编写一个函数:
def unpack(d, *keys)
return tuple(d[k] for k in keys)
然后执行:
a, b = unpack(f(), 'a', 'b')
实际上,这全都是矫kill过正。简单的方法会更好:
This is really all overkill though. Something simple would be better:
result = f()
a, b = result['a'], result['b']
这篇关于一次将Python字典的内容分配给多个变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文