简体   繁体   English

试试-除了Python中的KeyError块

[英]try - except KeyError block in Python

x is a tuple: (x1, x2) x是一个元组:(x1,x2)

try:
    clusters[bestmukey].append(x)  # statment 1
except KeyError:
    clusters[bestmukey] = [x]      # statement 2

(1) How do statement 1 and statement 2 do different things? (1)陈述1和陈述2如何做不同的事情?

(2) Why are the separated statements needed? (2)为什么需要分开的语句?

clusters[bestmukey].append(x) requires that clusters[bestmukey] already exist and be a list that can be appended to. clusters[bestmukey].append(x)要求clusters[bestmukey]已经存在并且是可以附加的列表。 If clusters does not have the right key, this will raise KeyError. 如果clusters没有正确的密钥,则会引发KeyError。

clusters[bestmukey] = [x] will always work (as long as clusters is a dictionary, which is what I'm assuming), and sets the value to a new list with one element. clusters[bestmukey] = [x]将始终有效(只要clusters是一本字典,这就是我所假设的),并将值设置为带有一个元素的新列表。

The effect of the code is to create a list with a new single value if the key does not already exist, or add the value to the existing list if it does already exist. 该代码的作用是,如果键不存在,则用新的单个值创建一个列表;如果该键不存在,则将该值添加到现有列表中。

The same effect could be achieved without a try/except by using a defaultdict . 不用try / except可以通过使用defaultdict获得相同的效果。 The defaultdict effectively wraps this logic into itself. defaultdict有效地将此逻辑包装到自身中。

Apparently clusters is a dict whose values are lists. 显然, clusters是其值为列表的dict This code tries to append to such a list if the key bestmukey exists, but if it does not, it adds the key and starts a list. 如果密钥bestmukey存在,则此代码尝试将其追加到这样的列表中,但如果不存在,它将添加密钥并启动一个列表。

It would usually be preferable to use a defaultdict 通常最好使用defaultdict

clusters[bestmukey] = ... in statement #2 will write to clusters[bestmukey] , no matter what (it's called an lvalue, a left value, something you assign to). clusters[bestmukey] = ... ,语句#2中的clusters[bestmukey] = ...都将写入clusters[bestmukey] (这称为左值,左值,您分配的值)。 However, clusters[bestmukey] in statement #1 is an rvalue (not something you assign to), and in Python's mind it needs to exist, or you get an error. 但是,语句#1中的clusters[bestmukey]是一个右值(不是分配给您的值),在Python看来,它必须存在,否则会出错。 Even if you didn't get an error (like in Ruby or other languages), you would not have gotten something that you can append on*, so statement #1 is not applicable. 即使您没有收到错误(例如Ruby或其他语言),也不会获得可以append在*上的内容,因此语句#1不适用。


*) You can, with defaultdict . *)您可以使用defaultdict But that's another story. 但这是另一个故事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM