本文章总结了董付国老师的Pthon程序设计(第2版)书的内容,仅供个人学习使用,如有侵权,立刻删除 by:mfdy
文章链接:mfdy’s blog: Python 序列
CSDN目录:https://blog.csdn.net/mofadiyu/article/details/90178542
集合为无序可变序列,不能有重复值
且集合中只能包含数字、字符串、元组等不可变类型数据
a = {3, 5}
a.add(7)
a_set = set(range(8,14))
>>> a_set
{8, 9, 10, 11, 12, 13}
>>> b_set = set([0, 1, 2, 3, 0, 1, 2, 3, 7, 8]) # 自动去除重复
>>> b_set
{0, 1, 2, 3, 7, 8}
>>> c_set = set() # 空集合
>>> c_set
set()
a = {1, 4, 2, 3}
>>> a.pop()
1
>>> a.pop()
2
>>> a.add(2)
>>> a
{4, 3, 2}
>>> a,remove(3)
>>> a
{2, 4}
Python集合支持交集、并集、差集等运算
a_set = set([8, 9, 10, 11, 12, 13])
b_set = {0, 1, 2, 3, 7, 8}
x = {1, 2, 3}
y = {1, 2, 5}
z = {1, 2, 3, 4}
>>> a_set | b_set
{0, 1, 2, 3, 7, 8, 9, 10, 11, 12, 13}
>>> a_set.union(b_set)
{0, 1, 2, 3, 7, 8, 9, 10, 11, 12, 13}
>>> a_set & b_set
{8}
>>> a_set.intersection(b_set)
{8}
>>> a_set - b_set
{9, 10, 11, 12, 13}
>>> a_set.difference(b_set)
{9, 10, 11, 12, 13}
>>> a_set ^ b_set
{0, 1, 2, 3, 7, 9, 10, 11, 12, 13}
>>> a_set.symmetric_difference(b_set)
{0, 1, 2, 3, 7, 9, 10, 11, 12, 13}
>>> x < y
False
>>> x < z
True
>>> y < z
False
>>> x.issubset(y)
False
>>> x.issubset(z)
True
作为集合的具体应用,可以使用集合快速提取序列中单一元素
如果使用传统方式
from random import randint
# 100个介于0~999之间的随机数
listRandom = [randint(0, 9999) for i in range(100)]
noRepeat = []
for i in listRandom:
if i not in noRepeat:
noRepeat.append(i)
>>> len(listRandom)
>>> len(noRepeat)
但是使用集合,只需要如下一行代码
newSet = set(listRandom)