python

    技术2022-07-11  70

    # 枚举 s = ['a', 'b', 'c'] for i, v in enumerate(s): print(i, v) # 创建迭代器 class TestIter(): def __init__(self,lst): self.lst = lst def __iter__(self): print('__iter__ is called') return iter(self.lst) # t = TestIter() t = TestIter([1,3,5,7,9]) for e in t: print(e) # 同理 for e in t.__iter__(): print(e) r = [1,2,3] for i in range(len(r)-1,-1,-1): print(r[i]) # 打包 # 聚合各个可迭代对象的迭代器: x = [3,2,1] y = ['a','b','c'] list(zip(x,y)) for i ,j in zip(y,x): print(i,j) # 过滤器 # 函数通过 lambda 表达式设定过滤条件,保留 lambda 表达式为True的元素: fil = filter(lambda x: x>10, [1,21,3,4,8,22]) for e in fil: print(e) # 链式操作 from operator import (add, sub) def add_or_sub(a,b,oper): return (add if oper=='+' else sub)(a,b) # split 分割 s = 'I love python'.split(' ') # replace 替代 s = 'I love python'.replace(' ', ',') # 反转字符串 st = 'python' ''.join(reversed(st)) import time seconds = time.time() # 当前时间 # 浮点数转时间结构体 local_time = time.localtime(seconds) # 时间结构体转时间字符串 str_time = time.asctime(local_time) # 时间结构体转指定格式时间字符串 format_time = time.strftime('%Y.%m%d %H:%M:%S', local_time) # 时间字符串转时间结构体 time.strptime(format_time,'%Y.%m.%d %H:%M:%S') # with 读写文件 import os,sys path = r'G:\Test' os.listdir(path) # 读文件 with open(path, mode='r',encoding='utf-8') as f: o = f.read() print(o) # 写文件 w_path = r'G:\Test\1.txt' with open(w_path, mode='w', encoding='utf-8') as f: w = f.write("I love python \n It\'s so simple") os.listdir() # 提取后缀名 import os os.path.splitext(w_path)

     

    Processed: 0.010, SQL: 9