Python: order in a set of numbers

跟風遠走 提交于 2019-12-11 08:27:03

问题


With this code:

print set(a**b for a in range(2, 5) for b in range(2, 5))

I get this answer:

set([64, 256, 4, 8, 9, 16, 81, 27])

Why it isn't sorted?


回答1:


Sets are not ordered collections in python or any other language for that matter.

Sets are usually implemented using hash keys (hash codes). So order is probably related to how hash functions are used instead of natural order of its elements.

If you need order, please do consider using a list.




回答2:


Sets are by their nature unordered containers. From the documentation:

A set object is an unordered collection of distinct hashable objects.

They are implemented using a hash table, facilitating O(1) membership tests. If you need an ordered set, try OrderedDict.fromkeys():

from collections import OrderedDict
OrderedDict.fromkeys(a**b for a in range(2, 5) for b in range(2, 5))


来源:https://stackoverflow.com/questions/8084825/python-order-in-a-set-of-numbers

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