我需要获取存储在变量中的键的值。变量的值会变化,输出模式也应据此变化。请检查下面的代码,我似乎没有得到输出。只有当我可以传递给定 key 的值时,我才能获得它们。如果您指出该程序中的任何其他错误,那就太好了,因为我对此非常陌生。谢谢:)
self = {
"1" : None,
"0" : "",
"2" : "abc",
"3" : "def",
"4" : "ghi",
"5" : "jkl",
"6" : "mno",
"7" : "pqrs",
"8" : "uvw",
"9" : "wxyz"
}
def rec(rest_of_no, path):
if not rest_of_no:
combinations.add(path)
return
first, rest = rest_of_no[0], rest_of_no[1:]
letters = self.get[int(first)]
for letter in letters:
rec(rest_of_no, path)
return combinations
t = int(input())
for i in range(t):
n = int(input())
ar = list(map(int, input().split()))
combinations = set()
rec(ar, "")
print (combinations)
这是我得到的错误:
Runtime Error:
Runtime ErrorTraceback (most recent call last):
File "/home/66ec1f75836d265709dd36b77f69f071.py", line 30, in <module>
rec(ar, "")
File "/home/66ec1f75836d265709dd36b77f69f071.py", line 19, in rec
letters=self[int(first)]
KeyError: 2
最佳答案
您的代码有一些问题。首先,为什么要使用eval
?
letters = self.get(first)
# will do just fine instead of
letters = self.get(eval('first'))
其次,self
字典的键(对于不是传递给方法的实例的随机变量来说,这是一个非常糟糕的名称)是字符串。但是 ar
包含整数,这就是为什么 first
是 int
并且 self.get(first)
返回 无
。
此外,正如 AndrejKesely 所指出的:
if not rec:
# should probably be
if not rest_of_no:
使用相同参数的递归调用将导致无限递归,而 return rec
返回一个函数对象,这可能不是您的意图。仍然需要大量调试;)
关于python - 如果它的键存储在变量中,如何获取字典中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51468492/