Python: order in a set of numbers

前端 未结 2 470
小鲜肉
小鲜肉 2020-12-12 06:07

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,         


        
2条回答
  •  我在风中等你
    2020-12-12 07:02

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

提交回复
热议问题