Heim  >  Artikel  >  Backend-Entwicklung  >  Python中集合类型(set)学习小结

Python中集合类型(set)学习小结

WBOY
WBOYOriginal
2016-06-10 15:18:121048Durchsuche

set 是一个无序的元素集合,支持并、交、差及对称差等数学运算, 但由于 set 不记录元素位置,因此不支持索引、分片等类序列的操作。

初始化

复制代码 代码如下:

s0 = set()
d0 = {}
s1 = {0}
s2 = {i % 2 for i in range(10)}
s = set('hi')
t = set(['h', 'e', 'l', 'l', 'o'])
print(s0, s1, s2, s, t, type(d0))

运行结果:
复制代码 代码如下:

set() {0} {0, 1} {'i', 'h'} {'e', 'o', 'l', 'h'}

提示
1.s0、d0:使用 {} 只能创建空字典,创建空集必须用 set();
2.ss、sl:set 中的元素是 无序不重复 的,可以利用这个特点去除列表中的重复元素。

运算操作

复制代码 代码如下:

print(s.intersection(t), s & t)  # 交集
print(s.union(t), s | t)   # 并集
print(s.difference(t), s - t)  # 差集
print(s.symmetric_difference(t), s ^ t) # 对称差集
print(s1.issubset(s2), s1 print(s1.issuperset(s2), s1 >= s2)      # 包含

运行结果:

复制代码 代码如下:

{'h'} {'h'}
{'l', 'h', 'i', 'o', 'e'} {'l', 'h', 'i', 'o', 'e'}
{'i'} {'i'}
{'i', 'l', 'o', 'e'} {'i', 'l', 'o', 'e'}
True True
False False

提示
1.非运算符的方法接受任何可迭代对象作为参数,如 s.update([0, 1]);
2.其他等价操作:s.update(t) 与 s |= t,s.intersection_update(t) 与 s &= t,s.difference_update(t) 与 s -= t,s.symmetric_difference_update(t) 与 s ^= t 等。

基本方法

复制代码 代码如下:

s = {0}
print(s, len(s))   # 获取集合中的元素的总数
s.add("x")         # 添加一个元素
print(s)
s.update([1,2,3])  # 添加多个元素
print(s, "x" in s) # 成员资格测试
s.remove("x")      # 去掉一个元素
print(s, "x" not in s) 
s.discard("x")     # 如果集合存在指定元素,则删除该元素
c = s.copy()       # 复制集合    
print(s, s.pop())  # 弹出集合中的一个不确定元素,如果原集合为空则引发 KeyError
s.clear()          # 删除集合中的元素
print(s, c)

运行结果:
复制代码 代码如下:

{0} 1
{0, 'x'}
{0, 'x', 1, 2, 3} True
{0, 1, 2, 3} True
{1, 2, 3} 0
set() {0, 1, 2, 3}
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn