简单来讲,序列是一种数据存储结构,用来存储一系列数据。在内存中,序列就是一块用来存放多个值的连续存储空间,存储的是对象的地址,而Python中一切皆对象。
常见的序列结构有:字符串、列表、元组、字典、集合。
可以把序列看成是拥有序列结构数据类型的祖先,因此序列具有的特点,上述五种序列结构也有。字符串,列表,元组具有序列的所有功能,字典、集合序列具有部分功能,当然五种序列结构除了序列特点之外还拥有各自独有的特点,比如数据表示形式([列表]、(元组,)、{字典或集合}),数据是否可变,内置方法等等。
序列的特点:
1.序列可以正向操作,也可以反向操作,因此可以使用切片功能。
2.序列类型的通用操作符。
3.序列类型的通用方法。
4.循环遍历:for---in
下面我们来分别测试这些切片、操作符、方法吧!
字符串、列表、元组具有上面三个图中的所有功能!
1.针对字符串的操作方法:字符串是不可变数据类型,不论怎么操作,原字符串不会改变,但是可以定义新的变量接收它。
a = "hello world"
a[10] # d
a[2:] # lo world
'h' in a # True
'h' not in a # False
" hello python" + a # ' hello pythonhello world'
a*3 # 'hello worldhello worldhello world'
len(a) # 11
min(a) # ' '
max(a) # 'w'
a.index('o') # 4
a.count('l') # 3
2.针对列表的操作方法:列表类型是可变数据类型,可以直接修改原本列表中的元素,原本列表也随之改变。
b = [1,2,3,4,5,6]
b[5] # 6
b[2:] # [3, 4, 5, 6]
2 in b # True
2 not in b # False
b = b + [7,8,9]
b # [1, 2, 3, 4, 5, 6, 7, 8, 9]
b*2 # [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
len(b) # 9
min(b) # 1
max(b) # 9
b.index(2) # 1
b.count(1) # 1
3.针对元组的操作方法:元组是不可变序列,不能修改元组中的元素
c = (1,2,3,4,5,6)
c[2:4] # (3, 4)
6 in c # True
6 not in c # False
c+(7,8,9) # 生成一个新的元组 ,(1, 2, 3, 4, 5, 6, 7, 8, 9)
c # 原元组没有改变,(1, 2, 3, 4, 5, 6)
c*2 # (1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6)
len(c) # 6
max(c) # 6
min(c) # 1
c.count(1) # 1
c.index(3) # 2
字典和集合具有上面三幅图的部分功能!
4.针对字典的操作方法:字典是“键值对”的无序可变的,可以通过“键对象”找到对应的对象。相比较字符串、列表、元组,字典不支持切片操作,也不支持 加号拼接和count、index方法等。
d = {"name":"张三","age":"18","job":"programmer"}
d["name"] # 键的名称相当于下标,张三
# d[0:2] # 不支持切片操作,TypeError: unhashable type: 'slice'
"name" in d # 键可以,True
"张三" in d # 键对应的值不可以
"张三" not in d # 取反,True
# d + {"address":"北极"} # TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
# d*2 # 字典的内部为哈希表,键不能重名, TypeError
len(d) # 3
max(d) # name
min(d) # age
# d.count("name") 不支持
# d.index("张三") 不支持
5.针对集合的操作方法:集合是无序可变,元素不能重复的,集合大体上和字典相似,底层实现就是字典,字典不支持的序列方法,集合也不支持。集合可以很好地实现数据去重操作,交并补差等操作。
e = {1,2,3,4,5,6,6,6}
e # 集合中不支持相同元素,所以6只有一个,因此集合很容易实现数据去重操作
# e[0] # 不支持索引
# e[2:4] # 不支持切片
3 in e
3 not in e
# e + {7,8,9} # 不支持,集合底层实现还是字典,字典不支持的集合也不支持
# e*2 不支持
len(e)
min(e)
max(e)
# e.count() 不支持
# e.index(2) 不支持
6.字符串、列表、元组、字典、集合的遍历:
a = "hello world" # 字符串
b = [1,2,3,4,5,6] # 列表
c = (1,2,3,4,5,6) # 元组
d = {"name":"张三","age":"18","job":"programmer"} # 字典
e = {1,2,3,4,5,6,6,6} # 集合
for item in a:
print(item,end=",")
print()
for item in b:
print(item,end=",")
print()
for item in c:
print(item,end=",")
print()
for item in d:
print(item,end=",")
print()
for item in e:
print(item,end=",")
print()
总结:字符串、列表、元组支持索引、切片、加号拼接、count方法、index方法,而字典和集合不支持这些方法,但其他方法支持。