- 论坛徽章:
- 0
|
Normal
0
7.8 磅
0
2
false
false
false
EN-US
ZH-CN
X-NONE
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:普通表格;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0cm 5.4pt 0cm 5.4pt;
mso-para-margin:0cm;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.5pt;
mso-bidi-font-size:11.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;
mso-font-kerning:1.0pt;}
Python 语法之集合
File information
2009-10-20
磁针石:xurongzhong#gmail.com
博客:
oychw.cublog.cn
参考资料:
《Python Essential Reference 4th
Edition 2009》
《beginning python from novice to
professional second edition 2008》
*特点:集合是无序的,且没有重复值。成员是固定长度的,set的长度可变,frozenset是固定长度的。它们共同的操作和方法如下:
项目
功能
len(s)
s.copy()
s.difference(t)
s-t
s.intersection(t)
交集 &
s.isdisjoint(t)
没有共同元素返回真
s.issubset(t)
是子集为真
s.issuperset(t)
是父集为真
s.symmetric_difference(t)
只在一个集合的元素 ^
s.union(t)
联合 |
注意并集(联合)不是使用加号,是使用逻辑的或。
针对set额外的方法
项目
功能
s.add(item)
s.clear()
s.difference_update(t)
保留s-t
s.discard(item)
同上,不过item是一个整体
s.intersection_update(t)
求交集存于s
s.pop()
s.remove(item)
s.symmetric_difference_update(t)
求出只在一个集合的元素存于s
s.update(t)
添加t中的元素至s
s =
set([3,5,9,10]) # Create a set of numbers
t =
set("Hello") # Create a set of unique characters
>>>
s
set([9,
10, 3, 5])
>>>
t
set(['H',
'e', 'l', 'o'])
支持的操作:
a = t |
s # Union of t and s
b = t
& s # Intersection of t and s
c = t –
s # Set difference (items in t, but not in s)
d = t ^
s # Symmetric difference (items in t or s, but not both)
添加:
t.add('x')
# Add a single item
s.update([10,37,42])
# Adds multiple items to s
移除:
t.remove('H')
>>> set(range(10))
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> set([0, 1, 2, 3, 0, 1, 2, 3, 4,
5])
set([0, 1, 2, 3, 4, 5])
>>> set(['fee', 'fie', 'foe'])
set(['foe', 'fee', 'fie'])
>>> a = set([1, 2, 3])
>>> b = set([2, 3, 4])
>>> a.union(b)
set([1, 2, 3, 4])
>>> a | b
set([1, 2, 3, 4])
>>> c = a & b
>>> c.issubset(a)
True
>>> c
True
>>> c.issuperset(a)
False
>>> c >= a
False
>>> a.intersection(b)
set([2, 3])
>>> a & b
set([2, 3])
>>> a.difference(b)
set([1])
>>> a - b
set([1])
>>> a.symmetric_difference(b)
set([1, 4])
>>> a ^ b
set([1, 4])
>>> a.copy()
set([1, 2, 3])
>>> a.copy() is a
False
>>> mySets = []
>>> for i in range(10):
... mySets.append(set(range(i,i+5)))
...
>>> reduce(set.union, mySets)
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13])
>>> a = set()
>>> b = set()
>>> a.add(b)
Traceback (most recent call last):
File "", line 1, in ?
TypeError: set objects are unhashable
>>> a.add(frozenset(b))
多用于一个集合作为另外一个集合的成员或者字典的key。
更多参考:(
http://python.org/doc/lib/types-set.html
)
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/21908/showart_2075130.html |
|