加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在Python 2.7.3中使用字典作为switch语句

发布时间:2020-12-20 12:40:20 所属栏目:Python 来源:网络整理
导读:我喜欢使用字典作为开关语句的一种形式,通过设置布尔值作为键.例: def f(a):... return {True: -a,a==0: 0,a 0: a}[True]... f(-3)3 f(3)3 f(0)0 键True用作else / default case,只有在没有其他键被评估为True时才返回.我猜这是假设迭代字典的某种评估顺序.
我喜欢使用字典作为开关语句的一种形式,通过设置布尔值作为键.例:

>>> def f(a):
...      return {True: -a,a==0: 0,a > 0: a}[True]
... 
>>> f(-3)
3
>>> f(3)
3
>>> f(0)
0

键True用作else / default case,只有在没有其他键被评估为True时才返回.我猜这是假设迭代字典的某种评估顺序.

现在看一下最新版本的分支机构2.6,2.7,3.1和3.2的最新版本release announcement from the Python team:

Hash randomization causes the iteration order of dicts and sets to be
unpredictable and differ across Python runs. Python has never
guaranteed iteration order of keys in a dict or set,and applications
are advised to never rely on it. Historically,dict iteration order
has not changed very often across releases and has always remained
consistent between successive executions of Python. Thus,some
existing applications may be relying on dict or set ordering.

这是否意味着使用dicts作为切换呼叫将不再可能?或者也许我应该使用任何其他类(如OrderedDict或其他东西)?或者也许我完全不在了,它根本不应该影响到这一点?

解决方法

你误解了这段代码是如何工作的.

您的词典只有两个键:True和False. True键可能存在多个冲突值,但在字典初始化时会解析.

字典查找没有迭代.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读