""" --*第二章 语法最佳实践--类级别以下*-- """ '''2.1 python的内置类型''' print(bytes([102, 111, 111])) print(bytes((102, 111, 111))) # b'foo' print(list(b'foo bar')) # [102, 111, 111, 32, 98, 97, 114] print(tuple(b'foo bar')) # (102, 111, 111, 32, 98, 97, 114) # 没有前缀的字符串都是 Unicode--统一码:可以容纳世界上所有文字和符号的字符编码方案--2bytes print(type(b'some Bytes')) # <class 'bytes'> # 将字符串对象编码为字节序列的方法 # str.encode(encoding,errors) bytes(source,encoding,errors) # 将bytes表示的二进制数据转换成字符串 # bytes.decode(encoding,errors) str(source,encoding,errors) # 字符串拼接 # 运行时间成本与字符串长度成二次函数关系 s = '' substrings = ['a', 'b', 'c', 'd'] for substring in substrings: s += substring print(s) # 代码可读性低 s = ''.join(substrings) print(s) # 在需要合并的多个字符串之间插入分隔符 ss = ','.join(substrings) print(ss) # 字符串格式化 str.format() % # 集合类型 # 1.列表与元组 # 列表动态 大小可以改变 元组不可变 一旦创建不可修改 # 链表双端append和pop操作复杂度都是O(1)的数据结构 # python内置collections模块 提供deque(双端队列) 需要使用双端列表时可以使用 # 列表推导 print([i for i in range(10) if i % 2 == 0]) # 枚举enumerate 获取索引 for i, element in enumerate(['one', 'two', 'three']): print(i, element) seasons = ['spring', 'summer', 'fall', 'winter'] print(list(enumerate(seasons))) # print(enumerate(seasons)) # 返回内存地址 # 合并多个列表 对两个大小相等的可迭代对象进行均匀遍历 for item in zip([1, 2, 3], [4, 5, 6]): print(item) # zip()函数返回的结果再次调用zip(),恢复原状 for item in zip(*zip([1, 2, 3], [4, 5, 6])): print(item) # a = zip([1, 2, 3], [4, 5, 6]) # print(a) # 序列解包 适用于任意序列 first, second, third = 'foo', 'bar', '100' print(first) print(second) print(third) # 可利用带星号的表达式获取单个变量中的多个元素 first, second, *rest = 0, 1, 2, 3 # 带星号的表达式可获取序列的剩余部分 print(first) # 0 print(second) # 1 print(rest) # [2, 3] first, *inner, last = 0, 1, 2, 3 # 带星号的表达式获取序列的中间部分 print(first) # 0 print(inner) # [1, 2] print(last) # 3 # 对嵌套序列进行解包,在遍历由序列构成的复杂数据结构时,非常实用 (a, b), (c, d) = (1, 2), (3, 4) print((a, b, c, d)) # 2.字典 # 类似列表推导式的字典推导创建新字典 squares = {number: number**2 for number in range(10)} print(squares) # keys(),values(),items()返回视图对象 # key()返回dict_keys对象,可查看字典的所有键 # value()返回dict_values对象,可查看字典的所有值 # item()返回dict_items对象可查看字典所有的(key,value)二元元祖 words = {'foo': 'bar', 'fizz': 'bazz'} items = words.items() print(items) words['spam'] = 'eggs' print(items) # keys = [key for key in words] # print(keys) keys = [] values = [] for key, value in words.items(): keys.append(key) values.append(value) print(keys) print(values) # 字典的底层数据结构是伪随机探测散列表 # collections提供名为OrderedDict的有序字典:有序插入存储有序字典 python3.6之后Dict都有序 from collections import OrderedDict print(OrderedDict((str(number), None) for number in range(5, 7)).keys()) dic1 = {} dic1['name'] = 'xiaoming ' dic1['sex'] = 'girl' dic1['years'] = '11' dic1['grade'] = '4' dic1['weight'] = '40' dic2 = OrderedDict() dic2['a'] = '4' dic2['b'] = '3' dic2['c'] = '1' dic2['e'] = '9' dic2['d'] = '0' for k, v in dic1.items(): print(k, v) # 结果有序 for k, v in dic2.items(): print(k, v) # 结果有序 # 字典可按照key或value进行排序 dict_sort_key = (sorted(dic2.items(), key=lambda t: t[0])) print(dict_sort_key) dict_sort_value = sorted(dic2.items(), key=lambda t: t[1]) print(dict_sort_value) # 输出 # [('a', '4'), ('b', '3'), ('c', '1'), ('d', '0'), ('e', '9')] # [('d', '0'), ('c', '1'), ('b', '3'), ('a', '4'), ('e', '9')] # 删除最后一个元素popitem() end_pop = dic1.popitem() print(end_pop) # ('weight', '40') print(dic1) # {'name': 'xiaoming ', 'sex': 'girl', 'years': '11', 'grade': '4'} # 弹出字典的第一个元素 end_pop2 = dic2.popitem(last=False) print(end_pop2) print(dic2) # 输出 # ('a', '4') # OrderedDict([('b', '3'), ('c', '1'), ('e', '9'), ('d', '0')]) # 指定一个key值,将其移到最后 dic2.move_to_end('b') # 无返回 print(dic2) # OrderedDict([('c', '1'), ('e', '9'), ('d', '0'), ('b', '3')]) # fromkeys用于创建一个词典 但是不负责保存 若要保存赋值给其他变量 fruits = OrderedDict() varies = ['apple', 'banana', 'orange'] dic_fruits = fruits.fromkeys(varies) print(dic_fruits) # OrderedDict([('apple', None), ('banana', None), ('orange', None)]) dic_fruits1 = fruits.fromkeys(varies, 1) print(dic_fruits1) # OrderedDict([('apple', 1), ('banana', 1), ('orange', 1)]) # 3.集合 # set():可变、无序、有限集合 其元素唯一,不可变对象 # frozenset():不可变、可哈希、无序集合 其元素唯一、不可变的对象 # 创建方式 a = set([1, 2, 3]) print(a, type(a)) b = {element for element in range(3)} print(b, type(b)) c = {1, 2, 3} print(c, type(c)) # 4.collections模块-超越基础集合类型 # namedtuple()工厂函数 带字段名的元组 from collections import namedtuple # 定义一个类 Fruits = namedtuple('fruits', ['color', 'wight', 'number']) # 创建一个对象 fruit = Fruits('red', '4kg', '10') print(fruit) # fruits(color='red', wight='4kg', number='10') milk_tea = namedtuple('milk_tea', 'ice size sweet') tea = milk_tea('yes', 'biggest', '5') print(tea) # milk_tea(ice='yes', size='biggest', sweet='5') # 特有属性 # 获取所有字段名 print(fruit._fields) # print(fruit._fields) print(tea._fields) # ('ice', 'size', 'sweet') # _make接受一个可迭代对象产生一个实例 fruit2 = Fruits._make(['yellow', '6kg', '9']) print(fruit2) # fruits(color='yellow', wight='6kg', number='9') print(fruit2.color) # deque双端队列 from collections import deque List = deque(['a', 'b', 'c', 'd']) List.append('e') print(List) # deque(['a', 'b', 'c', 'd', 'e']) aa = List.popleft() print(aa, List) # a deque(['b', 'c', 'd', 'e']) ee = List.pop() print(ee, List) # e deque(['b', 'c', 'd']) List.appendleft('a') print(List) # deque(['a', 'b', 'c', 'd'])
python高级编程 python 笔记1
最新推荐文章于 2024-07-12 19:06:42 发布