Python不在dict条件句中表现 [英] Python not in dict condition sentence performance

查看:105
本文介绍了Python不在dict条件句中表现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道有什么更好的思考速度和资源?链接到一些值得信赖的来源将不胜感激。

 如果键不在dictionary.keys()中:

  dictionary.get(key):


解决方案

d do

 如果键不在字典中:

因为diction被按键迭代。



其次,这两个语句不是等价的 - 第二个条件是如果相应的值为falsy( 0 [] 等),不仅仅是键不存在。



最后,第一种方法肯定更快,更多的是pythonic。函数/方法调用是昂贵的。如果您不确定, timeit


Does anybody know about what is better to use thinking about speed and resources? Link to some trusted sources would be much appreciated.

if key not in dictionary.keys():

or

if not dictionary.get(key):

解决方案

Firstly, you'd do

if key not in dictionary:

since dicts are iterated over by keys.

Secondly, the two statements are not equivalent - the second condition would be true if the corresponding values is falsy (0, "", [] etc.), not only if the key doesn't exist.

Lastly, the first method is definitely faster and more pythonic. Function/method calls are expensive. If you're unsure, timeit.

这篇关于Python不在dict条件句中表现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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