最新更新在此页面:http://blog.csdn.net/a_flying_bird/article/details/29214503
==================================================================
set的特点是:无序、元素唯一。
参考:
- 4. Built-in Types 4.9. Set Types — set, frozenset
- Programming Python, 3rd Edition.chm:20.3. Implementing Sets; 第4版是第18章,下载链接:
(比如)使用场景:当需要收集一系列的数据元素,而且要自动去除冗余项。此时就适合用set这个数据类型。
示例:增加元素、元素唯一性
$ python
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> s = set()
>>> s
set([])
>>> s.add(1)
>>> s
set([1])
>>> s.add(1)
>>> s
set([1])
>>> s.add(10)
>>> s
set([1, 10])
>>> s.add(5)
>>> s
set([1, 10, 5])
>>>
遍历每一个元素:
>>> s
set([1, 10, 5])
>>> for x in s:
... print x
...
1
10
5
>>>
如何对元素进行排序:set本身没有sort功能,但可以把sort转换成list,然后调用list.sort():
>>> list_of_s = list(s)
>>> list_of_s
[1, 10, 5]
>>> list_of_s.sort()
>>> list_of_s
[1, 5, 10]
>>>