在 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() }
如果您只需要使用几次,那么您可以坚持最初的建议:
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/