鍍金池/ 問答/Python  HTML/ Python中關(guān)于dict和set的輸出差異性問題應(yīng)該如何理解?

Python中關(guān)于dict和set的輸出差異性問題應(yīng)該如何理解?

本人Python初學(xué)者,在python3.6練習(xí)代碼發(fā)現(xiàn),dict輸出按照鍵值是有序的,而set集合輸出是無(wú)序的,換句話說(shuō)就是每次執(zhí)行dict和set的輸出,dict的都一樣,但是set的內(nèi)容不變而順序會(huì)有變化。為什么會(huì)有這樣的差異呢?
我查了一下是字典和集合的背后依托于散列表,散列表的工作原理我就不多說(shuō)了。我自己猜測(cè)是Python在內(nèi)部對(duì)于dict的輸出是做了一些額外的處理所以導(dǎo)致它和set在輸出上的差異,這么理解對(duì)嗎?希望有明白原理的大神幫助我解答一下,感激不盡!

回答
編輯回答
玄鳥

dict是字典,set是集合,集合很重要的特性,無(wú)序性,唯一性,確定性(就是確定某個(gè)元素是不是在該集合中)。
所以set輸出是無(wú)序的是沒有問題的。
至于dict與set的輸出差異,不會(huì)做出額外處理。

2018年4月2日 14:02
編輯回答
法克魷

python 3.6 的dict 是鍵是按順序存放的,具體可以看 python 官方文檔
New dict implementation

The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).

但是不應(yīng)該依賴 dict 鍵有序,因?yàn)橐院蟮陌姹究赡軙?huì)變化,可是使用 ordereddict 明確指定鍵有序

2017年5月2日 02:58
編輯回答
練命

你之前學(xué)過其他語(yǔ)言嗎?dictset都是通過hash實(shí)現(xiàn)的,所以原理上來(lái)說(shuō)都是無(wú)序的。

但是python3.6之后,Python的dict的是按key值存入的時(shí)間排序的,沒看過源碼,但我猜是額外維護(hù)了一個(gè)key的鏈表。

2017年5月29日 01:35