python 3.6 collections document mistake found?

不想你离开。 提交于 2019-12-25 01:08:52

问题


Hello I found that in python 3.6:

cnt = collections.Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
print(cnt)  # >>> Counter({'blue': 3, 'red': 2, 'green': 1})

in the document, it says 'elements() Return an iterator over elements repeating each as many times as its count. Elements are returned in arbitrary order.'

However:

print(list(cnt.elements()))  

will always give me:

['red', 'red', 'blue', 'blue', 'blue', 'green']

I don't think it is arbitrary order anymore, it kind of depends on the sequece of original data's occurrence:

cnt = collections.Counter(['red', 'green', 'red', 'blue', 'blue', 'blue'])
print(list(cnt.elements())) 
# >>> ['red', 'red', 'green', 'blue', 'blue', 'blue']

If I switch 'blue' and 'green' in the list, I will get 'green' before 'blue' in the cnt.elements()

Is my discovery correct or I was not doing it the right way?


回答1:


This is due to a change in the implementation of dict in Python 3.6:

The dict type now uses a “compact” representation based on a proposal by Raymond Hettinger which was first implemented by PyPy. The memory usage of the new dict() is between 20% and 25% smaller compared to Python 3.5.

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).




回答2:


Python 3.6 dict are now ordered!

Since collections.Counter is a direct subclass of the built-in type dict, it is stored in order as well.


As the python 3.6 update note stated that the order of the dict should not be relied on because it's only an implementation detail; you should not rely on the fact that .elements() returns ordered elements.

But as of Python 3.7, you can be sure that dict will always keep insertion order!



来源:https://stackoverflow.com/questions/47965481/python-3-6-collections-document-mistake-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!