【问题标题】:How do I get the value inside the dictionary if it's key is stored inside a variable?如果字典的键存储在变量中,如何获取字典中的值?
【发布时间】:2018-07-22 19:16:17
【问题描述】:

我需要获取存储在变量中的键的值。变量的值会发生变化,并且输出模式应该会因此而变化。请检查下面的代码我似乎没有得到输出。只有当我可以传递给定键的值时,我才能得到它们。如果您指出此程序中的任何其他错误,那就太好了,因为我对此很陌生。谢谢:)

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

【问题讨论】:

    标签: python python-3.x function loops dictionary


    【解决方案1】:

    与您的代码有关的几件事。首先,为什么要使用eval

    letters = self.get(first)  
    # will do just fine instead of
    letters = self.get(eval('first')) 
    

    其次,self 字典的键(对于不是传递给方法的实例的随机变量来说,这是一个非常糟糕的名称)是字符串。但是ar 包含整数,这就是为什么firstintself.get(first) 返回None

    此外,正如 AndrejKesely 指出的那样:

    if not rec:
    # should probably be 
    if not rest_of_no:
    

    并且具有相同参数的递归调用将导致无限递归,而return rec 返回一个函数对象,这可能不是您的意图。仍然需要大量调试;)

    【讨论】:

    • 还有其他错误,比如if not rec rec 是函数名。
    • 在类实例之外使用变量名self 也有点奇怪。
    • @AndrejKesely 是的。但这不会导致错误(或任何错误);)仍然添加它。
    • @schwobaseggl 最后,程序将进入无限递归,因为它在rec 中使用相同的参数rec(rest_of_no, path) 调用;)
    • @AndrejKesely 问题是,OP 询问了一个特定的错误,而不是调试他们的整个程序;)还有更多:return rec 很可能没有按照 OP 的预期去做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    相关资源
    最近更新 更多