将返回字典中的值赋给唯一变量

2024-10-04 07:28:25 发布

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

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

Tags: ofto方法appledictionaryreturnexampledef
2条回答

可能(取决于您如何使用dict),^{}也是一个解决方案:

from collections import namedtuple

color_dict = {'apple': 'red',
              'carrot':'orange',
              'grape':'green'}

# Create a namedtuple class
ColorMap = namedtuple('ColorMap', ['apple', 'carrot', 'grape'])

# Create an instance of ColorMap by using the unpacked dictionary
# as keyword arguments to the constructor
color_map = ColorMap(**color_dict)

# Unpack the namedtuple like you would a regular one
apple, carrot, grape = color_map

优势

  • namedtuples非常轻
  • 漂亮的点式属性访问(obj.attr

缺点

  • 要像我在最后一行中展示的那样使用解包,如果需要或不需要,您将始终需要解包所有值。也许这适用于你或其他人的用例,也许不是

当然,如果namedtuples符合要求,您可以完全跳过中间字典。你知道吗


背景

有些东西和你的玩具语法很相似

apple, grape = foodColors()['apple','grape'] # made up syntax

几乎有效:

apple, grape = foodColors().values()

(仅从dict中获取值列表,并将其像常规元组一样解包)。 问题是字典没有排序(它们的键/值对的顺序是任意的)。不是随机的(一点也不),而是任意的,顺序会改变as the dictionary's size changes)。你知道吗

然而,命名元组的字段是有序的(就像规则元组有顺序一样,在namedtuple中,它们只是命名的字段)。因此,在某种程度上,您可以获得字典以及元组等轻量级有序结构的一些好处。这就是为什么它们可以被解包成有序的序列。你知道吗

但是,如果这样做,则依赖于元组中字段的确切顺序,因此放弃了它们提供的一个巨大优势。更多关于namedtuples以及为什么它们很棒的信息,请参见雷蒙德·赫廷格的PyCon 2011: Fun with Python's Newer Tools。你知道吗

您可以使用operator.itemgetter

apple, grape = itemgetter('apple', 'grape')(foodColors())

当然,如果需要,可以重用itemgetter函数:

getter = itemgetter('apple', 'grape')
apple, grape = getter(foodColors())
apple2, grape2 = getter(foodColors())

相关问题 更多 >