【问题标题】:Check many keys in dictionary: optimization [duplicate]检查字典中的许多键:优化 [重复]
【发布时间】:2013-09-22 15:30:16
【问题描述】:

有没有更好的写法:

if "msg" in response_dic or "save_act_errors" in response_dic  or "add_act_errors" in response_dic  or "modif_act_errors" in response_dic  or "update_act_errors" in response_dic:
    #do stuff

response_dic 是字典,我正在检查键。

其实有2个问题:

1/ 如何测试字典中的多个键?

2/如何检查部分键(在我的情况下以“_act_errors”结尾)?

【问题讨论】:

  • 你是对的,这是一个类似的问题,但在我的情况下,我必须使用任何而不是全部。

标签: python dictionary key


【解决方案1】:

是的!有更好的办法:

keys = ["msg", "save_act_errors", "add_act_errors", "modif_act_errors", ...]

if any(key in response_dic for key in keys):
    #do stuff

【讨论】:

  • 好主意!写起来更短,但效率一样吗?
  • any() 与您所做的完全相同。当它找到第一个计算结果为True 的表达式时,它将停止并返回True,否则将返回False
【解决方案2】:
>>> keys = ['msg','save_act_errors']
>>> d = { 'msg':1 }
>>> any(key in d for key in keys)
True

或者

>>> keys | set(d)

【讨论】:

  • | 运算符需要两个 sets...此外,set(keys) & set(d) 更有意义!
  • any 运算符正是我所需要的。但我认为使用set 会更慢,对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
  • 2013-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多