数据容器
各种数据结构
列表(list)
my_list = ['Alex', 'Bob', True, [1, 2, 3]]
- 元素可以异类型, 支持嵌套, 可重复
- 有序: 下标索引 0, 1, 2, 3……
- 下标索引(反向) ……-3, -2, -1
print(my_list[1], my_list[-1][0])
# Bob 1
方法
- 查询下标: 返回索引, 不存在则报错
- 修改元素: 指定下标
- 插入元素: 指定下标, 指定元素
- 追加: 元素(容器)放到尾部 extend([29, 11])
- 删除:
- del
- pop() 默认最后一个元素
- remove(a) 从前到后, 仅删一个
- 统计: count(元素)
- 统计总数: len(my_list)
- 清空: clear()
index = my_list.index("Alex") # 0
my_list[0] = "Alice"
my_list.insert(2, "Charlie")
my_list.append('final')
my_list.extend(list2)
# ['Alice', 'Bob', 'Charlie', 2022, True, [1, 2, 3], 'final', 1949, 1989, 2019]
del list2[2] # [1949, 1989]
elem = my_list.pop(3) # 2022
my_list.remove(True)
# ['Alice', 'Bob', 'Charlie', [1, 2, 3], 'final', 1949, 1989, 2019]
list2.insert(1, 1989)
dup = list2.count(1989) # 2
num = len(my_list) # 8
my_list.clear()
# my_list == []
迭代
while循环:
i = 0
while i < len(my_list):
print(f"{i}: {my_list[i]}")
i += 1
for循环(依次序):
for ele in my_list:
print(ele)
元组(tuple)
不可修改的list
my_tuple = (1, "Hello", True)
t1 = tuple()
t2 = ((), )
- 但其中有list可以对内容赋值
t3 = (1, "NM$L", ["Alex", "Bob"])
t3[-1][0] = "Alice"
print(t3)
# (1, 'NM$L', ['Alice', 'Bob'])
字符串(string)
任意数量的字符 不可修改
my_str = "fight for freedom"
- 替换: replace("s0", "s1") s0替换为s1,得到新字符串
- 分隔: split("s2") 以s2为间隔切分,装入list中
- 规整: strip(" ") 去除首尾空格/指定字符串
- 查找子串出现次数
- 获取长度
my_str = "fight for freedom"
new_slogan = my_str.replace("for", "with")
print(new_slogan)
# fight with freedom 替换内容
str_list = my_str.split(" ")
print(str_list)
# ['fight', 'for', 'freedom']
print(my_str.strip('dom'))
# fight with free
序列-切片
取出子序列:序列[起始下标:结束下标:步长]
步长为负:反向取
str9 = "cdefgab"
print(str9[::2])
# cegb
集合(set)
多个数据:无序 去重 可修改
my_set = {"Alex", "Bob", "Alex"}
- 添加元素 add(el)
- 移除 remove(el)
- 随机取出 pop()
- 清空 clear()
- 取差集 set1.difference(set2) 得到新集合,为set1有 set2没有的
- 交集 set1.union(set2)
- 元素数量 len(my_set)
- for 遍历
my_set = {"Alex", "Bob", "Alex"}
set2 = {"Alex", "Bob", "Charlie"}
my_set.add(564)
print(my_set)
# element = my_set.pop()
# print(element)
print(my_set.difference(set2))
# my_set.difference_update(set2)
# print(my_set)
print(my_set.union(set2))
my_set.clear()
字典(dict)
key-value 键值对
原生:通过key值找value key唯一
my_dict = {"Alex": 564, "Bob": 8963, "Charlie": 1918}
value可嵌套
- 新增/更新 dict['A'] = 123
- 删除 pop('B')
- 清空 clear()
- 取全部key keys() 是list
- 遍历 for
my_dict = {"Alex": 564, "Bob": 8963, "Charlie": 1918}
print(my_dict["Alex"])
# 564
stu_dict = {"Alex": {"ch": 99, "Math": 101, "English": 120}, "Bob": {"ch": 101, "Math": 111, "English": 121}}
print(stu_dict["Alex"]["ch"])
# 99
my_dict["Daniel"] = 116
print(my_dict)
print(my_dict.pop("Alex"))
# 564
keys = list(my_dict.keys())
# 遍历字典
print(keys)
for k in my_dict:
print(f"{k}: {my_dict[k]}")
容器通用操作
- 元素个数 len(my_list)
- 最大/小元素 max(my_dict)
- 类型转换 不能转换成字典 list(my_set)
- 排序 sorted(my_list, [顺序])
- 返回list
- 降序
reverse=True