gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:13:57 26 4
gpt4 key购买 nike

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

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

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

# 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]]

但我觉得应该有一种更优雅的方式来做到这一点......

最佳答案

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

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

如果你不能,但你需要对该字典进行许多操作,那么预处理它可能是有意义的:

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

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

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

关于Python:使用解压元组作为(dict)键的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51535473/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com