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

后端 未结 2 925
鱼传尺愫
鱼传尺愫 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.

    0 讨论(0)
  • 2021-01-21 22:29

    I think what is confusing you is the symmetric nature of the tuples. Converting the list to a set has not affected the arrangement of items in the tuples but rather the order of the tuples. And that is because sets are unordered by nature. Here is another example with asymmetric tuples.

    >>> U = [(2.0, 0.0), (0.0, 1.0)]
    >>> set(U)
    {(0.0, 1.0), (2.0, 0.0)}
    
    0 讨论(0)
提交回复
热议问题