Python 3.6.3 按键错误

Python 3.6.3 KeyError

我想用 python3 中的 "try/catch" 块在 O(1) 时间内检查字典中是否存在元素。当我尝试这样做时,出现语法错误,我不确定原因:

try a_dict[i]:
    print(i) 
except KeyError:
    a_dict[i] = ... #some item

为简单起见,假设我有一个检查数组中重复项的函数,并且我有一个使用上述逻辑的函数:

def hasDuplicate(a):
    a_dict = dict()
    for i in a:
        # logic from above
        try a_dict[i]:
            print(i) 
        except KeyError:
            a_dict[i] = True
        # end of logic from above
    return -1

我会在 try 语句所在的行收到语法错误。

我想避免使用 in,因为它的检查时间为 O(N)。除非它检查字典的 O(1) 时间?任何帮助或反馈将不胜感激

语法应该是:

def hasDuplicate(a):
    a_dict = dict()
    for i in a:
        # logic from above
        try:
            print(a_dict[i])
        except KeyError:
            a_dict[i] = True
        # end of logic from above
    return -1

从你提到的 "try/catch" 我猜你来自 Java? :-)

I want to avoid using in because that checks in O(N) time. Unless it checks in O(1) time for a dictionary?

确实如此。字典是一个专门的哈希图,因此包含检查是一个分摊的 O(1)。

我想这就是你想要做的?如果你想查找重复项,则无需使用 try/catch.

def hasDuplicate(a):
    a_dict = dict()
    for i in a:
      # logic from above
      try:
        if a_dict[i]:
          print(i) 
      except KeyError:
        a_dict[i] = True
      # end of logic from above
    return -1


print(hasDuplicate([1, 2, 3, 4, 1])) //print duplicate value (i.e. 1 and will return -1)