Does converting a list to a set change the order o

2019-02-26 11:30发布

问题:

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 want to convert the list into a set. Any help?

Thanks

回答1:

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.



回答2:

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


标签: python list set