理解 set() 函数 [英] Understanding the set() function
问题描述
在python中,set()
是一个没有重复元素的无序集合.但是,我无法理解它是如何生成输出的.
例如,考虑以下内容:
<预><代码>>>>x = [1, 1, 2, 2, 2, 2, 2, 3, 3]>>>集合(x)设置([1, 2, 3])>>>y = [1, 1, 6, 6, 6, 6, 6, 8, 8]>>>设置(y)设置([8, 1, 6])>>>z = [1, 1, 6, 6, 6, 6, 6, 7, 7]>>>设置(z)设置([1, 6, 7])set(y)
的输出不应该是:set([1, 6, 8])
?我在 Python 2.6 中尝试了以上两个.
正如你所说,集合是无序的.尽管实现集合的一种方法是使用树,但它们也可以使用哈希表实现(意味着按排序顺序获取键可能不是那么简单).
如果你想对它们进行排序,你可以简单地执行:
sorted(set(y))
将生成一个包含集合元素的排序列表.(不是集合.同样,集合是无序的.)
否则,set
唯一保证的就是它使元素唯一(不会出现多次).
希望这会有所帮助!
In python, set()
is an unordered collection with no duplicate elements. However, I am not able to understand how it generates the output.
For example, consider the following:
>>> x = [1, 1, 2, 2, 2, 2, 2, 3, 3]
>>> set(x)
set([1, 2, 3])
>>> y = [1, 1, 6, 6, 6, 6, 6, 8, 8]
>>> set(y)
set([8, 1, 6])
>>> z = [1, 1, 6, 6, 6, 6, 6, 7, 7]
>>> set(z)
set([1, 6, 7])
Shouldn't the output of set(y)
be: set([1, 6, 8])
? I tried the above two in Python 2.6.
Sets are unordered, as you say. Even though one way to implement sets is using a tree, they can also be implemented using a hash table (meaning getting the keys in sorted order may not be that trivial).
If you'd like to sort them, you can simply perform:
sorted(set(y))
which will produce a sorted list containing the set's elements. (Not a set. Again, sets are unordered.)
Otherwise, the only thing guaranteed by set
is that it makes the elements unique (nothing will be there more than once).
Hope this helps!
这篇关于理解 set() 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!