Does converting a list to a set change the order of elements?

后端 未结 2 929
鱼传尺愫
鱼传尺愫 2021-01-21 21:31

When I do something like:

U = [(1.0, 0.0), (0.0, 1.0)]
set(U)

It gives me:

{(0.0, 1.0), (1.0, 0.0)}

I just w

2条回答
  •  悲哀的现实
    2021-01-21 22:22

    Sets are not ordered. Dictionaries are not ordered either. If you want to preserve a specific order, then use a list.

    >>> ''.join(set("abcdefg"))
    'acbedgf'
    >>> ''.join(set("gfedcba"))
    'acbedgf'
    >>> ''.join(set("1234567"))
    '1325476'
    >>> ''.join(set("7654321"))
    '1325476'
    

    Obviously, when you iterate over a set some kind of order has to come out. But the order is an arbitrary order which you cannot specify.

    Here's my favorite:

    >>> {'apple', 'banana'}
    {'banana', 'apple'}
    >>> {'banana', 'apple'}
    {'apple', 'banana'}
    

    The order is affected by hash collisions, so it's not only dependent on the contents of the set but the order of insertion too. But you have no real control over the order.

提交回复
热议问题