def foodColors():
"""Example function to return dictionary of food colors."""
appleColor = getAppleCol() # long magic function
return {'apple':appleColor, 'carrot':'orange', 'grape':'green'}
如果函数返回如上所示的字典,并且函数调用的时间比所需的时间长,那么将返回的值赋给唯一变量的最佳方法是什么?例如,我的应用程序不关心carrot颜色,也不知道foodColors()
是如何实现的。你知道吗
我现在做的很明显:
colorDict = foodColors()
apple = colorDict['apple']
grape = colorDict['grape']
这个方法很好,但我希望有人有更好的解决方案,或者能够展示一种独特的方式来内联解压返回值,例如:
apple, grape = foodColors()['apple','grape'] # made up syntax
可能(取决于您如何使用dict),^{} 也是一个解决方案:
优势
namedtuples
非常轻obj.attr
)缺点
当然,如果
namedtuples
符合要求,您可以完全跳过中间字典。你知道吗背景
有些东西和你的玩具语法很相似
几乎有效:
(仅从dict中获取值列表,并将其像常规元组一样解包)。 问题是字典没有排序(它们的键/值对的顺序是任意的)。不是随机的(一点也不),而是任意的,顺序会改变as the dictionary's size changes)。你知道吗
然而,命名元组的字段是有序的(就像规则元组有顺序一样,在
namedtuple
中,它们只是命名的字段)。因此,在某种程度上,您可以获得字典以及元组等轻量级有序结构的一些好处。这就是为什么它们可以被解包成有序的序列。你知道吗但是,如果这样做,则依赖于元组中字段的确切顺序,因此放弃了它们提供的一个巨大优势。更多关于
namedtuples
以及为什么它们很棒的信息,请参见雷蒙德·赫廷格的PyCon 2011: Fun with Python's Newer Tools。你知道吗您可以使用
operator.itemgetter
:当然,如果需要,可以重用itemgetter函数:
相关问题 更多 >
编程相关推荐