简体   繁体   English

为什么 iter() 在 Python 中对一个集合进行排序?

[英]Why iter() sorts in place a set in Python?

Calling iter() on a set in Python seems to sort the set in place.在 Python 中的集合上调用iter()似乎可以对集合进行排序。

Example:例子:

>>> my_set = {2, 1, 3}
>>> _ = iter(my_set)
>>> my_set
{1, 2, 3}

I am wondering why is that's the case.我想知道为什么会这样。 I guess it has something to do with the way __iter__ or __next__ are implemented for set in cPython but I am not sure.我想这与__iter____next__在 cPython 中实现set的方式有关,但我不确定。

Any idea is welcome.欢迎任何想法。


EDIT编辑

As pointed by answers and comments below, the _ = iter(my_set) does not change the results - my_set prints 'ordered'.正如下面的答案和评论所指出的, _ = iter(my_set)不会改变结果 - my_set打印“有序”。 The reasons are explained in details here .原因在这里详细解释。

without the _ = iter(my_set) the result is sorted also没有_ = iter(my_set)结果也被排序

>>> my_set = {2, 1, 3}
>>> my_set
{1, 2, 3}

Sets are unordered, which means they can appear in different orders when you call them.集合是无序的,这意味着当您调用它们时它们可以以不同的顺序出现。 See more here: https://www.w3schools.com/python/python_sets.asp在此处查看更多信息: https://www.w3schools.com/python/python_sets.asp

As stated by @S4eed3sm, using the {} creates a set which becomes unordered .正如@S4eed3sm 所述,使用{}创建一个变为unordered的集合。 However, that's not the point of the iterator.然而,这不是迭代器的重点。

By using an iterator, you can call the next() method on the iterator to get the next item in the iterator.通过使用迭代器,您可以在迭代器上调用next()方法来获取迭代器中的下一项。 That's the purpose of the iterator, not sorting the set.这是迭代器的目的,而不是对集合进行排序。

In case you want to sort a list, for example, you can use the sorted() method which is also built-in in python.例如,如果您想对列表进行排序,您可以使用同样内置在 python 中的sorted()方法。

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

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