是否可以 "unpack" 一次调用一个命令?
Is it possible to "unpack" a dict in one call?
我正在寻找一种以通用方式 "unpack" 字典的方法,并找到了 a relevant question(和答案),它解释了各种技术(TL;DR:它不太优雅)。
然而,这个问题解决了字典的键未知的情况,OP 想要将它们自动添加到本地命名空间。
我的问题可能更简单:我从一个函数中得到一个字典,并想即时分解它,知道我需要的键(我可能不是每次都需要所有键)。现在我只能做
def myfunc():
return {'a': 1, 'b': 2, 'c': 3}
x = myfunc()
a = x['a']
my_b_so_that_the_name_differs_from_the_key = x['b']
# I do not need c this time
当我在寻找
的等价物时
def myotherfunc():
return 1, 2
a, b = myotherfunc()
但是对于字典(这是我的函数返回的)。我不想使用后一种解决方案有几个原因,其中一个原因是哪个变量对应于哪个返回元素并不明显(第一种解决方案至少具有可读性的优点)。
可以这样操作吗?
如果确实需要,您可以使用 operator.itemgetter()
object 将多个键的值提取为元组:
from operator import itemgetter
a, b = itemgetter('a', 'b')(myfunc())
这还不够漂亮;我更喜欢显式和 可读 单独的行,您首先分配 return 值,然后 提取这些值。
演示:
>>> from operator import itemgetter
>>> def myfunc():
... return {'a': 1, 'b': 2, 'c': 3}
...
>>> itemgetter('a', 'b')(myfunc())
(1, 2)
>>> a, b = itemgetter('a', 'b')(myfunc())
>>> a
1
>>> b
2
你也可以使用地图:
def myfunc():
return {'a': 1, 'b': 2, 'c': 3}
a,b = map(myfunc().get,["a","b"])
print(a,b)
除了operator.itemgetter()
方法,你还可以自己写myotherfunc()
。它以所需键的列表作为参数,returns 是它们对应值的元组。
def myotherfunc(keys_list):
reference_dict = myfunc()
return tuple(reference_dict[key] for key in keys_list)
>>> a,b = myotherfunc(['a','b'])
>>> a
1
>>> b
2
>>> a,c = myotherfunc(['a','c'])
>>> a
1
>>> c
3
我正在寻找一种以通用方式 "unpack" 字典的方法,并找到了 a relevant question(和答案),它解释了各种技术(TL;DR:它不太优雅)。
然而,这个问题解决了字典的键未知的情况,OP 想要将它们自动添加到本地命名空间。
我的问题可能更简单:我从一个函数中得到一个字典,并想即时分解它,知道我需要的键(我可能不是每次都需要所有键)。现在我只能做
def myfunc():
return {'a': 1, 'b': 2, 'c': 3}
x = myfunc()
a = x['a']
my_b_so_that_the_name_differs_from_the_key = x['b']
# I do not need c this time
当我在寻找
的等价物时def myotherfunc():
return 1, 2
a, b = myotherfunc()
但是对于字典(这是我的函数返回的)。我不想使用后一种解决方案有几个原因,其中一个原因是哪个变量对应于哪个返回元素并不明显(第一种解决方案至少具有可读性的优点)。
可以这样操作吗?
如果确实需要,您可以使用 operator.itemgetter()
object 将多个键的值提取为元组:
from operator import itemgetter
a, b = itemgetter('a', 'b')(myfunc())
这还不够漂亮;我更喜欢显式和 可读 单独的行,您首先分配 return 值,然后 提取这些值。
演示:
>>> from operator import itemgetter
>>> def myfunc():
... return {'a': 1, 'b': 2, 'c': 3}
...
>>> itemgetter('a', 'b')(myfunc())
(1, 2)
>>> a, b = itemgetter('a', 'b')(myfunc())
>>> a
1
>>> b
2
你也可以使用地图:
def myfunc():
return {'a': 1, 'b': 2, 'c': 3}
a,b = map(myfunc().get,["a","b"])
print(a,b)
除了operator.itemgetter()
方法,你还可以自己写myotherfunc()
。它以所需键的列表作为参数,returns 是它们对应值的元组。
def myotherfunc(keys_list):
reference_dict = myfunc()
return tuple(reference_dict[key] for key in keys_list)
>>> a,b = myotherfunc(['a','b'])
>>> a
1
>>> b
2
>>> a,c = myotherfunc(['a','c'])
>>> a
1
>>> c
3