簡體   English   中英

dict() function 在 colab 和 jupyter notebook 之間的行為不同

[英]dict() function behaves differently between colab and jupyter notebook

Google 的 colab 和 jupyter notebook 對dict()的反應不同 function

木星筆記本:

!python --version
Python 3.7.6

代碼:

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

output:

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

谷歌實驗室:

!python --version
Python 3.6.9

代碼:

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

output:

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

你覺得為什么會有這樣的差異,難道也是版本問題?

python 3.7起,字典保持鍵的順序與其插入順序相同,所以回答你的問題,是的,這是因為版本。

這個想法是從 python3.6 開始提出的,但它仍然被認為是依賴於實現的:

這個新實現的順序保留方面被認為是一個實現細節,不應依賴(這可能會在未來發生變化,但在更改語言規范之前,希望在幾個版本中使用該語言的新 dict 實現為所有當前和未來的 Python 實現強制要求保持順序的語義;這也有助於保持與隨機迭代順序仍然有效的舊版本語言的向后兼容性,例如 Python 3.5)。

從 Python 3.7 開始,此要求是強制性的,並提升為語言規范。

Google colab python 現在是 3.7.12 版,行為仍然相同,所以@Jarvis 的回答是不正確的。

Google colab python 以正確的順序在內部存儲字典,當使用打印 function 顯示時使用正確的順序。 但是,使用 colab 顯示單元格中最后一個表達式的值時,它會按鍵對字典進行排序。 我的建議是始終使用 print() function。

代碼:

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

output:(注意順序有何不同)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM