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

无人久伴 提交于 2019-12-20 03:06:04

问题


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


来源:https://stackoverflow.com/questions/15800296/does-converting-a-list-to-a-set-change-the-order-of-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!