简体   繁体   English

Python:按一组数字排序

[英]Python: order in a set of numbers

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?为什么没有排序?

Sets are not ordered collections in python or any other language for that matter.集合不是 Python 或任何其他语言中的有序集合。

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.如果您需要订购,请考虑使用列表。

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.它们是使用哈希表实现的,便于 O(1) 成员资格测试。 If you need an ordered set, try OrderedDict.fromkeys() :如果您需要有序集,请尝试OrderedDict.fromkeys()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM