最新消息:码丁实验室,一站式儿童编程学习产品,寻地方代理合作共赢,微信联系:leon121393608。

Python的集合数据结构详解

Python 少儿编程 1913浏览 0评论

码丁实验室,一站式儿童编程学习产品,寻地方代理合作共赢,微信联系:leon121393608。

Python的集合数据结构详解

Python集合

建立一个集合

本例Python版本为Python3.4

>>> set([1, 2, 3, 4])        # 内置函数

>>> {1, 2, 3, 4}

集合中的值不可更改,但是还是可以向集合中添加元素的

集合中的元素是无序的,唯一的(该特性经常用于去重)

C:code> c:python34python

>>> set([1, 2, 3, 4])

{1, 2, 3, 4}

>>> set(‘spam’)

{‘s’, ‘a’, ‘p’, ‘m’}

>>> {1, 2, 3, 4}

{1, 2, 3, 4}

>>> S = {‘s’, ‘p’, ‘a’, ‘m’}

>>> S

{‘s’, ‘a’, ‘p’, ‘m’}

集合中添加元素

>>> S = set()        # 初始化一个空的集合

>>> S.add(1.23)

>>> S

{1.23}

集合的 交,并,补,子集

>>> engineers = {‘bob’, ‘sue’, ‘ann’, ‘vic’}

>>> managers  = {‘tom’, ‘sue’}

>>> ‘bob’ in engineers             # in操作符

True

>>> engineers & managers     #交集

{‘sue’}

>>> engineers | managers       #并集

{‘bob’, ‘tom’, ‘sue’, ‘vic’, ‘ann’}

>>> engineers – managers

{‘vic’, ‘ann’, ‘bob’}

>>> managers – engineers

{‘tom’}

>>> engineers > managers     #超集

False

>>> {‘bob’, ‘sue’} < engineers  #子集

True

>>> (managers | engineers) > managers

True

>>> managers ^ engineers

# 只有一种职务,而不是身兼两职,类似于xor(比特操作)

{‘tom’, ‘vic’, ‘ann’, ‘bob’}

>>> {1, 2, 3} | {3, 4}#并集

{1, 2, 3, 4}

>>> {1, 2, 3} | [3, 4]

TypeError: unsupported operand type(s) for |: ‘set’ and ‘list’

#并集操作只能应用于两个集合,而不能是一个集合,一个是列表

>>> {1, 2, 3}.union([3, 4])

{1, 2, 3, 4}

>>> {1, 2, 3}.union({3, 4})

{1, 2, 3, 4}

>>> {1, 2, 3}.union(set([3, 4]))

{1, 2, 3, 4}

>>> {1, 2, 3}.intersection((1, 3, 5))#交集

{1, 3}

>>> {1, 2, 3}.issubset(range(-5, 5))#子集

True

集合用来过滤序列中重复元素

>>> L = [1, 2, 1, 3, 2, 4, 5]

>>> set(L)

{1, 2, 3, 4, 5}

>>> L = list(set(L))   # 去重

>>> L

[1, 2, 3, 4, 5]

>>> list(set(['yy', 'cc', 'aa', 'xx', 'dd', 'aa']))

# 顺序可能会变化

['cc', 'xx', 'yy', 'dd', 'aa']

判断集合相等

>>> L1, L2 = [1, 3, 5, 2, 4], [2, 5, 3, 4, 1]

>>> L1 == L2  # 序列是有顺序的

False

>>> set(L1) == set(L2)# 集合没有顺序

True

>>> sorted(L1) == sorted(L2)

# 排序之后

True

>>> ‘spam’ == ‘asmp’, set(‘spam’) == set(‘asmp’), sorted(‘spam’) == sorted(‘asmp’)

(False, True, True)

 

您必须 登录 才能发表评论!