将列表转换为集合会改变元素的顺序吗? [英] Does converting a list to a set change the order of elements?

查看:794
本文介绍了将列表转换为集合会改变元素的顺序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我做类似的事情时:

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

它给了我:

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

我只想将列表转换为一组.有帮助吗?

I just want to convert the list into a set. Any help?

谢谢

推荐答案

不对集合进行排序.也不对字典进行排序.如果要保留特定顺序,请使用列表.

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'

很显然,当您遍历一组 some 时,必须发出某种命令.但是该顺序是您无法指定的任意顺序.

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.

这是我的最爱:

>>> {'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.

这篇关于将列表转换为集合会改变元素的顺序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆