colors = ['black', 'white'] sizes = ['S', 'M', 'L'] tshirts = [(color, size) for color in colors for size in sizes] tshirtss = (('%s %s') % (color, size) for color in colors for size in sizes) print(tshirts) for i in tshirtss: print(i) symbols = '$¢£¥€¤' codes = [ord(symbol) for symbol in symbols] c = tuple((ord(symbol) for symbol in symbols)) print(codes) print(c) t = (20, 8) print(divmod(*t)) a, b, *c = range(5) print(a,b,c) fmt = '{:}'.format(12323) print(fmt) print('{:^14}'.format('陈某某')) print('{:>14}'.format('陈某某')) print('{:<14}'.format('陈某某')) print('{:*<14}'.format('陈某某')) print('{:&>14}'.format('陈某某'))#填充和对齐^<>分别表示居中、左对齐、右对齐,后面带宽度 print('{:.1f}'.format(4.234324525254)) print('{:.4f}'.format(4.1)) print('{:.2f}'.format(4.2222326)) print('{:^12}'.format("阿斯蒂芬")) print('{:o}'.format(250)) print('{:,}'.format(100000000)) print('{:,}'.format(235445.234235)) print('{名字}abc{性别}'.format(名字="曾智超",性别="男")) print('{0}abc{1}'.format("曾智超","男")) #具名元组 import collections City = collections.namedtuple('City', 'name country population coordinates') tolyo1 = City._make(('Tokyo', 'JP', 36.933, (35.689722, 139.691667))) print(tolyo1._asdict()) tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667)) print(tolyo1) print(tokyo) print(tokyo.coordinates) print(City._fields) #切片赋值 l = list(range(10)) print(l) l[2:5]=[2, 2, 2] print(l) del l[2:5] print(l) l[3::2] = [9,8] print(l) l[2:5] = (100,100) #如果被赋值的对象是一个切片,那么赋值必须是一个可迭代的对象,即便是一个单独数值,也应变为可迭代序列 print(l) #对序列使用+ 和 * l = [[1,2,3,'abc'],[4,5,6]] l = 3*l print(l) l[0][1]='X' print(l) #序列的增量赋值 *= 、+=(__iadd__) 可变序列上面一般实现了__iadd__方法,不可变序列上则没有 def p(x): return print(x) l = [1, 2, 3] p(id(l)) l *= 2 p(id(l)) p(l) l = (1, 2, 3) p(id(l)) l *= 2 p(id(l)) p(l) #+=谜题 t = (1, 2, [30, 40]) t[2].extend([50 ,60]) print(t) import dis p(dis.dis('s[a] += b')) ''' Tips: 不要将可变对象放入元组中 查看Python的字节码 增量赋值不是一个原子操作 ''' #2.7 list.sort方法和内置函数sorted ''' 返回None来表示就地进行的改变(list.sort) sorted新建一个列表作为返回值 ''' fruits = ['grape', 'rasphberry', 'apple', 'banana'] p(sorted(fruits,key=len)) p(fruits) list.sort(fruits) p(fruits) #2.8 用bisect来管理自己已排序的序列 import bisect import random def grade(score, break_score=[60, 70, 80, 90], grades='FDCBA'): return grades[bisect.bisect_right(break_score, score)] print([grade(score) for score in [83, 92, 100, 50, 30, 72]]) SIZE = 7 random.seed(1) my_list = [] for i in range(SIZE): new_item = random.randrange(SIZE*2) bisect.insort(my_list, new_item) print("%2d ->" % new_item, my_list) #当列表不是首选时,比如存放一个只包含数字的列表,数组可能是个好的选择 import array import random data = array.array('d', (random.random() for i in range(10**2))) print(data[-1]) fb = open('data.bin', 'wb') data.tofile(fb) fb.close() data2 = array.array('d') fp = open('data.bin', 'rb') data2.fromfile(fp, 10**2) fp.close() print(data2[-1]) #Numpy和Scipy import numpy as np #data = np.loadtxt('data.txt',encoding='UTF-8') #print(data[-3:]) #使用deque from collections import deque p = range(10) print(p) data = deque(range(10),maxlen=10) print(data) data.rotate(3) print(data) #字典(dict)和集合(set) import collections my_dist = {} print(isinstance(my_dist,collections.abc.Mapping)) ''' 什么是可散列类型 一个对象是可散列的,在对象生命周期中,散列值是不变的! 需事先实现__hash__()和__qe__()方法,两个散列对象如果相等,得到的散列值是一样的 Python中不可变类型都是可散列的 映射的key只能是可散列的 ''' a = dict(one=1, two=2, three=3) b = {'one':1, 'two':2, 'three':3} c = dict({'one':1, 'two':2, 'three':3}) d = dict([('one', 1), ('two', 2), ('three', 3)]) p = zip(['one', 'three', 'two'], [1, 3, 2]) e = dict(p) print(a==b==c==d==e) #字典推导 dictcomp D_CODES = [(86, 'China'), (91, 'India'), (1, 'United States'), (62, 'Indonesia'), (55, 'Brazil'), (92, 'Pakistan'), (880, 'Bangladesh'), (234, 'Nigeria'), (7, 'Russia'), (81, 'Japan')] p = {code:country for code, country in D_CODES} #字典推导式 print(p) print(dict(D_CODES)) q = {country.upper():code for code, country in p.items() if int(code)<64} print(q) # my_dist.setdefault(key,[]).append(new_value) #映射的弹性查询 1.利用defaultdict 2.自定义dict子类,重写__miss__()方法 class StrKeyDict0(dict): def __missing__(self, key): if isinstance(key, str): raise KeyError(key) return self[str(key)] def get(self, key, default=None): try: return self[key] except KeyError: return default def __contains__(self, key): return key in self.keys() or str(key) in self.keys() a = StrKeyDict0({'one':1, '1':1, '2':'two'}) #字典的变种 collections.OrderedDict #添加键的时候会保持顺序,删除的时候会删除末尾也就是最后一个加入的元素 collections.ChainMap p = collections.Counter('aaabbbcccddewffjjll') print(p) p.update('aaa') print(p) collections.UserDict #让用户来写dict的子类的!~ #不可变映射类型 from types import MappingProxyType pi = {'A':65} pi_proxy = MappingProxyType(pi) print(pi_proxy) #pi_proxy['B'] = 66 pi['B'] = 66 print(pi_proxy) p = frozenset(range(10)) q = set(range(10)) print(p) print(q) #集合操作 p = {i for i in range(10)} print(p) DIAL_CODES = [(86, 'China'),(91, 'India'),(1, 'United States'),(62, 'Indonesia'),(55, 'Brazil'), (92, 'Pakistan'),(880, 'Bangladesh'),(234, 'Nigeria'),(7, 'Russia'),(81, 'Japan'),] d1 = dict(DIAL_CODES) print("d1:", d1.keys()) d2 = dict(sorted(DIAL_CODES)) print("d2:", d2.keys()) print(d1 == d2) #人类使用文本 计算机使用字节序列 s = 'café' print(len(s)) b = s.encode('utf-8') #用utf-8将str对象编码成bytes对象 print(b) print(len(b)) print(b.decode('utf-8')) p = bytes.fromhex('31 4B CE A9') #解析十六进制,构建二进制序列 print(p) p = bytes('café',encoding='utf-8') print(p) cafe_crr = bytearray(p) print(cafe_crr) print(cafe_crr[-1:]) import array numbers = array.array('h', [-2, -1, 0, 1, 2]) #短整数16位 octets = bytes(numbers) print(octets) #结构体和内存视图 # coding: cp1252 print('Olá, Mundo!') u16 = 'El Niño'.encode('utf_16') print(u16) print(list(u16)) u16 = 'El Niño'.encode('utf_16le') print(u16) print(list(u16)) fp = open('cafe.txt', 'w', encoding='utf-8') #open采用文本模式,返回一个TextIOWrapper对象 print(fp) fp.write('café') fp.close() import os print(os.stat('cafe.txt').st_size) #UTF-8 编码的 'é' 占两个字节 fp2 = open('cafe.txt') print(fp2) print(fp2.read()) fp3 = open('cafe.txt', encoding='utf_8') print(fp3) print(fp3.read()) fp4 = open('cafe.txt', 'rb') #在二进制模式中读取文件, 返回BufferReader对象 print(fp4) print(fp4.read()) #返回对应的字节序列 import sys, locale expressions = """ locale.getpreferredencoding() type(my_file) my_file.encoding sys.stdout.isatty() sys.stdout.encoding sys.stdin.isatty() sys.stdin.encoding sys.stderr.isatty() sys.stderr.encoding sys.getdefaultencoding() sys.getfilesystemencoding() """ my_file = open('dummy', 'w') for expression in expressions.split(): value = eval(expression) # eval将str当做表达式求值并返回结果 print(expression.rjust(30), '->', repr(value)) # repr返回一个对象的string格式 # s1 = 'café' s2 = 'cafeu0301' print(s1, s2) print(len(s1), len(s2)) print(s1 == s2) #不同的码位序列 from unicodedata import name micro = 'μ' micro_cf = micro.casefold() print(name(micro)) #对非ASCII码排序使用的是 local.strxfrm 函数 fruits = ['caju', 'atemoia', 'cajá', 'açaí', 'acerola'] print(sorted(fruits)) import locale #locale.setlocale(locale.LC_COLLATE, 'pt_BR.UTF-8') sorted_fruits = sorted(fruits, key=locale.strxfrm) print(sorted_fruits) #PyUCA 使用Unicode排序算法排序 def factroial(n): '''return n!''' return 1 if n < 2 else n*factroial(n-1) print(factroial(42)) print(factroial.__doc__) print(type(factroial)) help(factroial) print(list(map(factroial, range(6)))) print([factroial(n) for n in range(6)]) print(list(map(factroial, filter(lambda n : n%2, range(6))))) print([factroial(n) for n in range(6) if n%2]) print(all([1, 1, 1])) print(any([0, 1, 1])) fruits = ['strawberry', 'fig', 'apple', 'cherry', 'raspberry', 'banana'] print(sorted(fruits,key=lambda a:a[::-1])) print(str,abs,123) print([callable(n) for n in [str,abs,123]]) #用户定义的可调用类型 import random class BingoCage: def __init__(self,items): self._items = list(items) random.shuffle(self._items) def pick(self): return self._items.pop() def __call__(self, *args, **kwargs): return self.pick() p = BingoCage(range(6)) print(p._items) print(p.pick()) print(p()) print(dir(factroial)) #从定位参数到仅限关键字参数 def f(a, *, b): return (a, b) print(f(1, b=2)) ''' 为什么引入激活函数 答:如果不用激活函数,很容易看到每一层的输出是上一层的输入的线性函数,那么 多层的隐含层就没有实际的效果,容易看到多层隐含层后得到的输出与单个隐含层得 到的输出是一样的,也就没有了深层网络的意义。 ''' #函数注解 作用:为IDE和lint程序等工具中的静态类型检查功能提供额外的类型信息 def clip(text:str, max_len:'int > 0'=80) -> str: """在max_len前面或后面的第一个空格处截断文本 """ end = None if len(text) > max_len: space_before = text.rfind(' ', 0, max_len) if space_before >= 0: end = space_before else: space_after = text.rfind(' ', max_len) if space_after >= 0: end = space_after if end is None: # 没找到空格 end = len(text) return text[:end].rstrip() print(clip.__annotations__) from inspect import signature sig = signature(clip) #返回Signature对象 print(sig.return_annotation) print(type(sig.parameters)) for i in sig.parameters.values(): print(type(i)) #参数名映射到Parameter对象 note = repr(i.annotation).ljust(13) print(note, ':', i.name, '=', i.default) #支持函数式编程的包