简体   繁体   English

在python中创建集合的元组是否总是导致相同的元组

[英]Does creating a tuple of a set in python always result in the same tuple

In my code, i convert a set to a tuple in order to use it as a dictionary key. 在我的代码中,我将集合转换为元组,以便将其用作字典键。 Since a set does not have an order and a tuple is, it would seem that: 由于集合没有顺序,而元组则有顺序,因此似乎:

tuple(some_set)

does not guarantee the same tuple every time, since an order has to be created. 由于必须创建订单,因此不能每次都保证相同的元组。 However, by testing this in practice it seems that a given set is converted to the same tuple each time, as demonstrated by the following code printing 1. 但是,通过在实践中进行测试,似乎每次将给定的集合转换为相同的元组,如以下代码打印1所示。

my_tuples = set()

for i in range(100000000):
    my_tuples.add(tuple(set(range(100))))


print(len(my_tuples))

I could not find any documentation about this, but does the tuple() function always return the same tuple on a given set? 我找不到与此有关的任何文档,但是tuple()函数是否总是在给定集合上返回相同的元组吗? And is this somewhere explicitly stated? 并且在某处有明确说明吗?

Sets are not "randomly" ordered, they are ordered based on an internal logic that may change (eg in different Python versions). 集合不是“随机”排序的,它们是根据可能发生变化的内部逻辑排序的(例如,在不同的Python版本中)。 This internal logic should be ignored during development, and you should consider a set as not having any order. 在开发过程中应忽略此内部逻辑,并且您应将集合视为没有任何顺序。

Indeed, 确实,

set([-1,-2]) == set([-2,-1]) # is True

but

tuple(set([-1,-2])) == tuple(set([-2,-1])) # is False

If you have a look at what the two tuples are, you'll find that tuple(set([-1,-2])), tuple(set([-2,-1])) is ((-1, -2), (-2, -1)) . 如果您看一下这两个元组是什么,您会发现tuple(set([-1,-2])), tuple(set([-2,-1]))((-1, -2), (-2, -1))

So, the insertion order of the elements in a set influences how they are subsequently iterated upon, and since tuple() is based on the iterator of the set, the results are the ones you see above. 因此,集合中元素的插入顺序会影响它们随后进行迭代的方式,并且由于tuple()基于集合的迭代器,因此结果就是您在上面看到的结果。

Finally, if you're not going to change "context" (eg python version) and the creation of the sets always occurs under the same circumstances, you can safely assume that the order of the elements will be the same ( beware, though, that this may be acceptable when scripting something that you will throw away tomorrow, but not anywhere else ). 最后,如果您不打算更改“上下文”(例如python版本),并且总是在相同的情况下创建集合,则可以放心地假定元素的顺序将相同( 但是请注意,在编写明天将要扔掉的东西的脚本时,这可能是可以接受的,但在其他地方则不能 )。

Integers hash to themselves : 整数对自己散列:

example=[5,0,1,2,3,4]
print(set(example))

output: 输出:

{0, 1, 2, 3, 4, 5}

It's not that hard to come up with examples of sets of integers which won't be in sorted order. 拿出不会按排序顺序排列的整数集的示例并不难。

example=[-5,0,1,2,3,4]
print(set(example))

output: 输出:

{0, 1, 2, 3, 4, -5}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM