2018-04-20 python集合set()操作(转)

http://www.iplaypy.com/jichu/set.html
Python set是基本数据类型的一种集合类型,它有可变集合(set())和不可变集合(frozenset)两种。创建集合set集合set添加集合删除交集并集差集的操作都是非常实用的方法。

创建集合set

python set类是在python的sets模块中,大家现在使用的python2.7.x中,不需要导入sets模块可以直接创建集合。

>set('boy')
set(['y', 'b', 'o'])

集合添加、删除

python 集合的添加有两种常用方法,分别是add和update。
集合add方法:是把要传入的元素做为一个整个添加到集合中,例如:

>>> a = set('boy')
>>> a.add('python')
>>> a
set(['y', 'python', 'b', 'o'])

集合update方法:是把要传入的元素拆分,做为个体传入到集合中,例如:

>>> a = set('boy')
>>> a.update('python')
>>> a
set(['b', 'h', 'o', 'n', 'p', 't', 'y'])

例如

集合删除操作方法:remove和discard

set(['y', 'python', 'b', 'o'])
>>> a.remove('python')
>>> a
set(['y', 'b', 'o'])

>>> a
set([1, 2, 3, 'python', 'h', 'o', 'n', 'p', 't', 'y'])
>>> a.discard('python')
>>> a
set([1, 2, 3, 'h', 'o', 'n', 'p', 't', 'y'])

python set() 集合操作符号、数学符号

集合的交集、合集(并集)、差集,了解python集合set与列表list的这些非常好用的功能前,要先了解一些集合操作符号

2018-04-20 python集合set()操作(转)_第1张图片
python 集合操作符号

简单的演示下差集、交集和合集的概念:


2018-04-20 python集合set()操作(转)_第2张图片
集合的交集、合集、差集

可变集合python set是www.iplaypy.com玩蛇网python学习交流平台,初期python学习中比较能接触到的。像列表、字典、字符串这类可迭代的对像都可以做为集合的参数。set集合是无序的,不能通过索引和切片来做一些操作。

你可能感兴趣的:(2018-04-20 python集合set()操作(转))