python - 如果字典的键存储在变量中,如何获取字典中的值?
问题描述
我需要获取存储在变量中的键的值。变量的值会发生变化,并且输出模式应该会因此而变化。请检查下面的代码我似乎没有得到输出。只有当我可以传递给定键的值时,我才能得到它们。如果您指出此程序中的任何其他错误,那就太好了,因为我对此很陌生。谢谢 :)
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
是 anint
和self.get(first)
返回的原因None
。
此外,正如 AndrejKesely 所指出的:
if not rec:
# should probably be
if not rest_of_no:
并且具有相同参数的递归调用将导致无限递归,同时return rec
返回一个函数对象,这可能不是您的意图。仍然需要大量调试;)
推荐阅读
- flutter - 使用 IconButton Flutter TextField
- php - 从 mysqli_query 返回不满足条件
- ckeditor - 通过 Chrome 在 CKEditor 中复制粘贴 GUI
- java - 为什么在java中,如果在命令行编译的main方法main的参数中给出“*”,这被认为是“a”
- nativescript - Need help changing Text of label in TS Code
- python - How to keep major-order when copying or groupby-ing a pandas DataFrame?
- json - JSON Nested dynamic structures Go decoding
- python - is there a way to get a more clear and successive edge with opencv in python?
- javascript - Add delay inside function
- java - 如何在 ModelMapper 的 AbstractConverter.convert() 方法中到达目标对象