python - 如果它的键存储在变量中,如何获取字典中的值?

标签 python python-3.x function loops dictionary

我需要获取存储在变量中的键的值。变量的值会变化,输出模式也应据此变化。请检查下面的代码,我似乎没有得到输出。只有当我可以传递给定 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 包含整数,这就是为什么 firstint 并且 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/

相关文章:

python - 如何为 Alpine 编译 python?

python - 输入命令将输入​​作为 int 而不是 Python 中的 str

python - 使用 '' 与 open、reader '' 函数

python - 如何在一个文件中存储多个networkx图?

javascript - 为什么我的功能只是闪烁并带我返回主页?

javascript - 有没有办法用 javascript 从字符串创建函数?

c - 在 C 中将 "thread entry point"函数调用为 "normal"函数是一种错误的代码实践吗?

python - 在 Python、MATLAB 等中使用 eval

python - 我如何进行分组并查看该组的所有成员是否都满足特定条件?

python - 如何使用 Panda 中的第一列保存结果