课程学习笔记参考https://coding.imooc.com/class/200.html(__bobby前辈所讲)
1序列类型的分类
容器序列 list tuple deque 可以放置任意类型的数据
扁平序列 str bytes bytearray array.array
可变序列 list deque bytearray array
不可变 str stuple bytes
2序列的abc继承关系
"Sequence", "MutableSequence",
3系列的+,+=与extend的区别
+=只需要是可迭代的类型即可
a = [1,2]
c = a + [3,4]
print(c)
#就地加
a += (3,4)
print(a)
a = [1,2]
a.extend(range(3))
print(a)
a.append((1,2))
print(a)
>>>>>>>>>>>>>>>>>>>>>>>
[1, 2, 3, 4]
[1, 2, 3, 4]
[1, 2, 0, 1, 2]
[1, 2, 0, 1, 2, (1, 2)]
4实现可切片的对象
import numbers
class Group:
#支持切片操作
def __init__(self, group_name, company_name, staffs):
self.group_name = group_name
self.company_name = company_name
self.staffs = staffs
def __reversed__(self):
self.staffs.reverse()
def __getitem__(self, item):
cls = type(self)
if isinstance(item, slice):
return cls(group_name=self.group_name, company_name=self.company_name, staffs=self.staffs[item])
elif isinstance(item, numbers.Integral):
return cls(group_name=self.group_name, company_name=self.company_name, staffs=[self.staffs[item]])
def __len__(self):
return len(self.staffs)
def __iter__(self):
return iter(self.staffs)
def __contains__(self, item):
if item in self.staffs:
return True
else:
return False
staffs = ["bobby1", "imooc", "bobby2", "bobby3"]
group = Group(company_name="imooc", group_name="user", staffs=staffs)
reversed(group)
for user in group:
print(user)
>>>>>>>>.
bobby3
bobby2
imooc
bobby1
5bisect管理可排序序列
import bisect
from collections import deque
#用来处理已排序的序列,用来维持已排序的序列, 升序
#二分查找
inter_list = deque()
bisect.insort(inter_list, 3)
bisect.insort(inter_list, 2)
bisect.insort(inter_list, 5)
bisect.insort(inter_list, 1)
bisect.insort(inter_list, 6)
print(bisect.bisect_left(inter_list, 4))
print(inter_list)
>>>>>
3
deque([1, 2, 3, 5, 6])
- bisect.bisect_left(a,x, lo=0, hi=len(a)) :
查找在有序列表 a 中插入 x 的index。lo 和 hi 用于指定列表的区间,默认是使用整个列表。如果 x 已经存在,在其左边插入。返回值为 index。
6什么时候不用列表
array和list的一个重要区别, array只能存放指定的数据类型
7列表推导式 生成器表达式 字典推导式
列表推导式 [name.upper() for name in names if len(name)>3]
生成器推导式 将上述两表推导式的[]改成(),即可得到生成器。
字典生成推导式 { key_expr: value_expr for value in collection if condition }
集合生成推导式 squared = {x**2 for x in [1, 1, 2]}
8 本章小结