【问题标题】:dict() function behaves differently between colab and jupyter notebookdict() 函数在 colab 和 jupyter notebook 之间的行为不同
【发布时间】:2020-12-26 06:53:39
【问题描述】:

Google 的 colab 和 jupyter notebook 对 dict() 函数的反应不同

Jupyter 笔记本:

!python --version
Python 3.7.6

代码:

trial=[(1, 250), (3, 275), (5, 290), (2, 300), (4, 500)]
dict(trial)

输出:

{1: 250, 3: 275, 5: 290, 2: 300, 4: 500}

Google Colab:

!python --version
Python 3.6.9

代码:

trial=[(1, 250), (3, 275), (5, 290), (2, 300), (4, 500)]
dict(trial)

输出:

{1: 250, 2: 300, 3: 275, 4: 500, 5: 290}

你觉得为什么会有这样的区别,会不会也是版本问题?

【问题讨论】:

  • 字典未排序。

标签: python jupyter-notebook google-colaboratory


【解决方案1】:

python 3.7 开始,字典保持键的顺序与其插入顺序相同,所以回答你的问题,是的,这是因为版本。

这个想法是从python3.6开始提出来的,但还是被认为是implementation dependent

这个新实现的顺序保留方面被认为是一个实现细节,不应依赖(这可能会在未来发生变化,但希望在更改之前在几个版本中使用该语言的这个新 dict 实现语言规范为所有当前和未来的 Python 实现强制要求保持顺序的语义;这也有助于保持与随机迭代顺序仍然有效的旧版本语言的向后兼容性,例如 Python 3.5)。

从 Python 3.7 开始,此要求是强制性的,并已提升为语言规范。

【讨论】:

    【解决方案2】:

    Google colab python 现在是 3.7.12 版本,行为仍然相同,所以@Jarvis 的回答不正确。

    Google colab python 在内部以正确的顺序存储字典,并且在使用打印功能显示时使用正确的顺序。但是,使用 colab 显示单元格中最后一个表达式的值,它按键对 dict 进行排序。我的建议是始终使用 print() 函数。

    代码:

    trial=[(1, 250), (3, 275), (5, 290), (2, 300), (4, 500)]
    dct_trial = dict(trial)
    print(dct_trial)
    dct_trial
    

    输出:(注意顺序如何不同)

    {1: 250, 3: 275, 5: 290, 2: 300, 4: 500}
    {1: 250, 2: 300, 3: 275, 4: 500, 5: 290}
    

    【讨论】:

      猜你喜欢
      • 2016-06-26
      • 2021-04-04
      • 2021-01-22
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 2021-04-09
      • 1970-01-01
      • 2020-03-30
      相关资源
      最近更新 更多