1. 序列
(1) 定义
序列是指内容连续、有序、可使用下标索引的一类数据容器,列表 元组 字符串均为序列
(2) 序列的切片
(3) 切片的例子
1.
python">my_list = [1, 2, 3, 4, 5]
tmp_list = my_list[1:4:1]
print(f"{tmp_list}")
2.
python">my_tuple = (1, 2, 3, 4, 5)
tmp_tuple = my_tuple[::1]
print(f"{tmp_tuple}")
3.
python">my_str = "123456789"
tmp_str = my_str[::2]
print(f"{tmp_str}")
4. 等同于反转序列
python">my_str = "123456789"
tmp_str = my_str[::-1]
print(f"{tmp_str}")
5.
python">my_list = [1, 2, 3, 4, 5]
tmp_list = my_list[3:1:-1]
print(f"{tmp_list}")
6.
python">my_tuple = (1, 2, 3, 4, 5)
tmp_tuple = my_tuple[::-2]
print(f"{tmp_tuple}")
7. 练习,取出字符串中的doinb
python">my_str = "super bniod carry"
my_str1 = my_str[6:11]
print(f"{my_str1}")
my_str2 = my_str1[::-1]
print(f"{my_str2}")
2. 集合(集合会自动去重)
(1) 定义
注意:集合中内容不能重复且无序
(2) 集合的常用操作
1. 集合无序,不支持下标索引
2. add——给集合中添加一个新的元素
python">my_set = {1, 2, 3, 4, 5}
my_set.add(6)
print(f"{my_set}")
3. remove——移除一个特定元素
python">my_set = {1, 2, 3, 4, 5}
my_set.remove(2)
print(f"{my_set}")
4. pop——从集合中随机取出一个元素
python">my_set = {1, 2, 3, 4, 5}
element_1 = my_set.pop()
element_2 = my_set.pop()
print(f"{my_set}, {element_1}, {element_2}")
5. clear——清空集合
python">my_set = {1, 2, 3, 4, 5}
my_set.clear()
print(f"{my_set}")
6. 集合1.difference(集合2)——取两个集合的差集,集合1有而集合2没有
python">my_set1 = {1, 2, 3} my_set2 = {1, 3, 4} my_set3 = my_set1.difference(my_set2) print(f"{my_set1}") print(f"{my_set2}") print(f"{my_set3}")
7. 集合1.difference_update(集合2)——消除集合1中与集合2相同的元素,得到新的元素
python">my_set1 = {1, 2, 3}
my_set2 = {1, 3, 4}
my_set3 = my_set1.difference_update(my_set2)
print(f"{my_set1}")
print(f"{my_set2}")
print(f"{my_set3}")
8.集合1.union(集合2)——将集合1与集合2合并起来
python">my_set1 = {1, 2, 3}
my_set2 = {1, 3, 4}
my_set3 = my_set1.union(my_set2)
print(f"{my_set1}")
print(f"{my_set2}")
print(f"{my_set3}")
9. len——统计集合元素个数(注意:只统计去重后的元素个数)
python">my_set1 = {1, 2, 3}
num = len(my_set1)
print(f"{num}")
10. 集合的遍历for(集合不支持下标索引,无法用while索引)
python">my_set1 = {1, 2, 3}
for i in my_set1:print(f"{i}")
(3) 集合特点
(4) 练习
有一个列表my_list = ["doinb", "tian", "doinb", "lwx", "gimgoon", "crisp", "lwx", "doinb"]
python">my_list = ["doinb", "tian", "doinb", "lwx", "gimgoon", "crisp", "lwx", "doinb"]
my_set = set()for i in my_list:my_set.add(i)print(f"{my_set}")
3. 字典
(1) 定义
注意:字典中key不可重复,且字典不支持下标索引,只支持key匹配
(2) 使用字典key取到对应的值
python">my_dict = {"doinb":100, "lwx":20, "crisp":1}
value = my_dict["doinb"]
print(f"{value}")
(3) 字典的嵌套以及访问嵌套字典元素
python">FPX_SCORE = {"doinb":{"语文":100,"数学":100,"英语":100,},"tian":{"语文": 101,"数学": 102,"英语": 103,},"lwx":{"语文": 104,"数学": 105,"英语": 106,},"gimgoon":{"语文": 103,"数学": 130,"英语": 120,},"crisp":{"语文": 120,"数学": 109,"英语": 123,},
}
lwx_math = FPX_SCORE["lwx"]["数学"]
doinb_english = FPX_SCORE["doinb"]["英语"]
print(f"{FPX_SCORE}")
print(f"{lwx_math}")
print(f"{doinb_english}")