集合
概述
是由多个或零个数据项的无序组合,用大括号{}表示,可以进行增删改操作。集合中元素类型不可重复。列表、字典和集合等类型不能作为集合元素出现。
s = {'102.12','32','str','1010'}
print(type(s))
print(len(s))
print(s)
<class 'set'>
4
{'str', '32', '102.12', '1010'}
可以看出,set为集合类型。
由于集合元素是不可重复的,所以可以集合类型来过滤重复数据。
s = {'102.12','32','str','1010',1010,'32'}
print(s)
{'32', '102.12', 1010, '1010', 'str'}
由此也可以看出由于集合是无序的,输出的顺序或许与原来不同。
s = set('知之为知之,不知为不知')
print(s)
{',', '不', '之', '为', '知'}
集合的运算
集合有交集(&)、并集(|)、差(-)和补(^)运算。
运算 | 含义 |
---|---|
S&V | 返回S和V共有的元素 |
S并V | 返回S和V中所有的元素 |
S-V | 返回在集合S但不在集合V中的元素 |
S^V | 返回S和V中所不同的元素 |
s = {'102.12','32','str','1010',1010}
v = {'102.12','42',1011,'python'}
print(s&v)
print(s-v)
print(s|v)
print(s^v)
{'102.12'}
{1010, '1010', 'str', '32'}
{1010, 'python', '102.12', 'str', '32', 1011, '42', '1010'}
{'python', 'str', '1010', 1010, 1011, '32', '42'}
集合的常见操作函数
s = {'102.12','32','str','1010',1010}
print(s)
s.add('python')#在集合中添加新的元素‘python’
print(s)
s.remove(1010)# 在集合中去掉元素1010
print(s)
print(len(s))# 获取集合的长度
print('python' in s)# 判断元素是否在集合中
print('32' not in s)
{'102.12', 'str', 1010, '1010', '32'}
{'102.12', 'str', 1010, '1010', 'python', '32'}
{'102.12', 'str', '1010', 'python', '32'}
5
True
False
序列类型
概述
序列类型是一维的元素向量,元素之间存在先后关系(注意与集合的区分),通过序号访问。可以重复,字符串、元组和列表类型都属于序列类型。
序列的常见操作函数
ls = ['python','world','hello','32','1011','32']
print(len(ls)) # 获取列表ls的长度
print('hello' in ls) # 判断元素是否在列表中
print('world' not in ls)
print(ls[2]) # 获取索引为2的元素
print(ls[-3:-1]) # 反向递减来索引 注意-3要在-1前面,否则索引为空
print(ls.index('hello')) # 获取元素hello的索引
print(ls.count('32')) # 计算元素’32‘出现的次数
print(ls*2) # 将列表元素复制一遍
t = ['12','54','65']
print(ls+t) # 将两个列表的元素相连接。
6
True
False
hello
['32', '1011']
2
2
['python', 'world', 'hello', '32', '1011', '32', 'python', 'world', 'hello', '32', '1011', '32']
['python', 'world', 'hello', '32', '1011', '32', '12', '54', '65']
列表
列表是由0个或多个元组组成的有序序列,可以进行增删改操作。元素可以是不同的类型。列表用中括号[ ]括起来。可以通过list(x)将x转化为字符串或集合转化为列表类型。
列表的索引
ls = ['python','world','hello','32','1011','32']
print(ls[2])
print(ls[-3:-1]) # 注意左闭右开
for i in ls:
print(i)
hello
['32', '1011']
python
world
hello
32
1011
32
列表的切片
获得列表的一个片段,即一个或多个元素。切片后的结果也是列表类型。
列表的切片有以下两种形式
ls = ['python','world','hello','32','1011','32']
print(ls[-3:-1]) # 注意左闭右开
print(ls[0:5:2])# 0:5为索引从第一个元素到第五个元素 注意左开右闭 步长为2
['32', '1011']
['python', 'hello', '1011']
映射类型
映射类型是键值数据对的组合,每个元素是无序的。