python dict:get vs setdefault [英] python dict: get vs setdefault

查看:314
本文介绍了python dict:get vs setdefault的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个表达式似乎与我相当。哪一个更好?

The following two expressions seem equivalent to me. Which one is preferable?

data = [('a', 1), ('b', 1), ('b', 2)]

d1 = {}
d2 = {}

for key, val in data:
    # variant 1)
    d1[key] = d1.get(key, []) + [val]
    # variant 2)
    d2.setdefault(key, []).append(val)

结果是一样的,但哪个版本更好还是更多的pythonic?

The results are the same but which version is better or rather more pythonic?

个人我发现版本2更难理解,至于我setdefault是非常棘手的把握。如果我正确理解,它会在字典中查找键的值,如果不可用,则将[]输入到dict中,返回值或[]的引用,并将val附加到参考。虽然肯定是顺利的,至少不直观(至少对我来说)。

Personally I find version 2 harder to understand, as to me setdefault is very tricky to grasp. If I understand correctly, it looks for the value of "key" in the dictionary, if not available, enters "[]" into the dict, returns a reference to either the value or "[]" and appends "val" to that reference. While certainly smooth it is not intuitive in the least (at least to me).

在我看来,版本1更容易理解(如果可用,获取key,如果没有,则获取[],然后加入由[val]组成的列表,并将结果放在key中)。但是,虽然更直观的理解,我担心这个版本的性能不太好,所有的这个列表创建。另一个缺点是d1在表达式中出现两次,这相当容易出错。可能有一个更好的实现使用get,但目前它不包括我。

To my mind, version 1 is easier to understand (if available, get the value for "key", if not, get "[]", then join with a list made up from [val] and place the result in "key"). But while more intuitive to understand, I fear this version is less performant, with all this list creating. Another disadvantage is that "d1" occurs twice in the expression which is rather error-prone. Probably there is a better implementation using get, but presently it eludes me.

我的猜测是,版本2虽然更难以掌握没有经验,但更快,因此优选的。意见?

My guess is that version 2, although more difficult to grasp for the inexperienced, is faster and therefore preferable. Opinions?

推荐答案

你的两个例子做同样的事情,但这并不意味着 get setdefault 做。

Your two examples do the same thing, but that doesn't mean get and setdefault do.

两者之间的区别基本上是手动设置 d [key] 指向每次列表,而 setdefault 只有在未设置的情况下才自动将 d [key] 设置到列表中。

The difference between the two is basically manually setting d[key] to point to the list every time, versus setdefault automatically setting d[key] to the list only when it's unset.

使两种方法尽可能相似,我从timeit import timeit
$运行

Making the two methods as similar as possible, I ran

from timeit import timeit

print timeit("c = d.get(0, []); c.extend([1]); d[0] = c", "d = {1: []}", number = 1000000)
print timeit("c = d.get(1, []); c.extend([1]); d[0] = c", "d = {1: []}", number = 1000000)
print timeit("d.setdefault(0, []).extend([1])", "d = {1: []}", number = 1000000)
print timeit("d.setdefault(1, []).extend([1])", "d = {1: []}", number = 1000000)

并获得

0.794723378711
0.811882272256
0.724429205999
0.722129751973

所以 setdefault 比这个目的的 get 快10% e。

So setdefault is around 10% faster than get for this purpose.

get 方法允许您比 setdefault 。您可以使用它来避免在密钥不存在时(如果这将会频繁发生)即使您不想设置密钥也不会得到一个 KeyError

The get method allows you to do less than you can with setdefault. You can use it to avoid getting a KeyError when the key doesn't exist (if that's something that's going to happen frequently) even if you don't want to set the key.

请参阅使用'setdefault'dict方法 dict.get()方法返回的情况有关这两种方法的更多信息的指针

关于 setdefault 的线索得出结论,大多数当时,你想使用一个 defaultdict 。关于的线程得到得出结论,它是缓慢的,通常你最好(速度明智)进行双重查找,使用defaultdict或处理错误(取决于字典的大小和用例)。

The thread about setdefault concludes that most of the time, you want to use a defaultdict. The thread about get concludes that it is slow, and often you're better off (speed wise) doing a double lookup, using a defaultdict, or handling the error (depending on the size of the dictionary and your use case).

这篇关于python dict:get vs setdefault的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆