Python:使用解包元组作为(dict)键的通用方法

2024-05-15 07:39:53 发布

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

在python中,我们可以解压函数参数,以便获得各个元素:

def printAll(*args):
    print(args, *args)  # packed and unpacked version respectively
printAll(1)  # (1,) 1
printAll(1, 2)  # (1, 2) 1 2

但是,我想定义一个函数,该函数(除其他外)使用一些参数访问某个容器(比如dict)。 dict是预定义的,不能修改! 我遇到了以下问题:

# e.g. d is a dict with
#    d[1] = 1 <- key is scalar
#    d[1, 2] = 3 <- key is tuple
def accessDict(name, *args):
    print('Hello', name)
    d[args]
    # d[*args] what I'd need, but it's invalid syntax
accessDict('foo', 1)  # should give 1 but gives KeyError because args is (1,) not 1
accessDict('foo', 1, 2)  # should give 3

另一种选择是添加:

if len(args) == 1:
    return d[args[0]]

但我觉得应该有一个更优雅的方式来做这件事。。。你知道吗


Tags: key函数namefooisdefargs函数参数
3条回答

首先,如SergeBallesta's solution中所述,您应该考虑将字典键重新定义为一致的元组。你知道吗

否则,您可以使用dict.get来使用回退:

d = {1: 1, (1, 2): 3}

def accessDict(name, *args):
    return d.get(args[0], d.get(args))

accessDict('foo', 1)     # 1
accessDict('foo', 1, 2)  # 3

如果这是真正的瓶颈,并且不太可能出现这种情况,那么可以使用try/except

def accessDict(name, *args):
    try:
        return d[args[0]]
    except KeyError:
        return d[args]

在我看来,最后一个版本是最具Python性的。如果它像鸭子一样呱呱叫,那就是鸭子。无需检查长度/类型等

首先,默认情况下python方法参数是tuple。你知道吗

在您的情况下,不能使用arg作为字典键,因为它不作为字典的键存在。因此,如果您想这样做,您需要从元组中提取每个键并将其分配给字典。你知道吗

此代码可能会帮助您。你知道吗

d = {1: 1, (1, 2): 3}
def accessDict(name, *args):
   print('Hello', name)


 #So simple edit is
   for a in args:
       d[a] #1, 3 


accessDict('foo', 1) 
accessDict('foo', (1, 2)) 

正确的方法是使用一致的键,例如:

d = {(1,): 1, (1, 2): 3}

如果不能,但需要处理该dict上的许多操作,则可以对其进行预处理:

d = {1: 1, (1, 2): 3}
dd = { (k if isinstance(k, tuple) else (k,)): v for k, v in d.items() }

如果你只需要使用几次,那么你可以坚持你最初的建议:

def accessDict(name, *args):
    print('Hello', name)
    d[args if len(args) > 1 else d[args[0]]]

相关问题 更多 >