Python3编程技巧
高效处理数据类型方法:
In [1]: from random import randint In [2]: data=[randint(-10,10) for _ in range(10)] In [3]: data Out[3]: [-3, -4, 3, 4, 7, -2, -4, 1, 7, -9] #过滤列表中的负数 In [9]: list(filter(lambda x:x>=0,data)) Out[9]: [3, 4, 7, 1, 7] [for x in data if x>=0] # 列表生成式解法 [x for x in data if x>=0] #哪个更快,列表解析更快,远快于迭代 In [15]: %timeit [x for x in data if x>=0] 581 ns ± 23.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In [16]: %timeit filter(lambda x:x>=0,data) 237 ns ± 4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) #得到20个同学的成绩 d={x:randint(60,100)for x in range(1,21)} #字典解析式,iteritems同时迭代字典, # #得到分数大于90的同学 {k:v for k,v in d.items() if v>90} #集合解析 In [35]: {x for x in s if x %3 ==0} Out[35]: {-9, -3, 3} #为元祖中的每个元素命名,提高程序可读性 #元祖存储空间小,访问速度快 #定义常量 NAME = 0 AGE=1 SEX=2 EMAIL=3 #拆包用法,定义类似其他语言的枚举类型,也就是定义数值常量 NAME,AGE,SEX,EMAIL=range(4) #案例 student=('Jim',16,'male','jin@163.com') #name print(student[0]) #age print(student[1]) #通过常量可以优化为 print(student[NAME]) print(student[AGE]) #namedtuple是继承自tuple的子类,namedtuple和tuple比较有更酷的特性 #namedtuple创建一个和tuple类似的对象,而且对象拥有可以访问的属性。这对象更像带有数据属性的类,不过数据属性是只读的。 from collections import namedtuple Student = namedtuple('Student',['name','age','sex','email']) s=Student('Jim',16,'male','jim@163.com') s.name s.age #统计序列中元素出现的频度 from random import randint data=[randint(0,20) for _ in range(30)] #创建字典{0:0,1:0,...} #方法1 c=dict.fromkeys(data,0) In [52]: for x in data: ...: c[x]+=1 #方法2,统计词频 from collections import Counter c2=Counter(data)#讲序列传入Counter的构造器,得到Counter对象是元素频度的字典 #使用most_common统计词频 In [58]: c2.most_common(3) Out[58]: [(10, 4), (20, 3), (8, 3)] #统计英文作文词频 import re txt=open('emmmm.txt').read() #分割后赋给Counter c3=Counter(re.split('\W',txt)) #找到频率最高的10个单词 c3.most_common(10) #内置函数是以c的速度运行,如sorted from random import randint d={x:randint(60,100) for x in 'xyzabc'} #{'a': 91, 'b': 65, 'c': 76, 'x': 85, 'y': 84, 'z': 72} # sorted(d) In [15]: zip(d.values(),d.keys()) Out[15]: <zip at 0x108b34dc8> In [16]: list(zip(d.values(),d.keys())) Out[16]: [(68, 'x'), (70, 'y'), (77, 'z'), (72, 'a'), (65, 'b'), (69, 'c')] #快速找到多个字典中的公共键 #In [1]: from random import randint,sample In [2]: sample('abcdefg',3) Out[2]: ['c', 'a', 'b'] In [4]: sample('abcdefg',randint(3,6)) Out[4]: ['b', 'a', 'd'] In [5]: s1={x:randint(1,4)for x in sample('abcdefg',randint(3,6))} In [9]: s1 Out[9]: {'a': 1, 'b': 2, 'c': 3, 'f': 3, 'g': 3} In [10]: s1={x:randint(1,4)for x in sample('abcdefg',randint(3,6))} In [11]: s1 Out[11]: {'b': 2, 'd': 3, 'g': 3} In [12]: s1 Out[12]: {'b': 2, 'd': 3, 'g': 3} In [13]: s2={x:randint(1,4)for x in sample('abcdefg',randint(3,6))} In [15]: s3={x:randint(1,4)for x in sample('abcdefg',randint(3,6))} #for循环遍历方法,找到s2,s3都有的k In [19]: res=[] In [20]: for k in s1: ...: if k in s2 and k in s3: ...: res.append(k ...: ) ...: ...: In [21]: res Out[21]: ['b'] #通过字典的keys()方法,找到三个字典同样的key In [26]: s1.keys()&s2.keys()&s3.keys() Out[26]: {'b'} #通过map得到一个迭代器对象 #In [27]: map(dict.keys,[s1,s2,s3]) Out[27]: <map at 0x108891b70> In [28]: list(map(dict.keys,[s1,s2,s3])) Out[28]: [dict_keys(['g', 'd', 'b']), dict_keys(['g', 'a', 'c', 'b', 'f']), dict_keys(['d', 'f', 'b', 'c', 'e', 'a'])] #通过reduce取出同样结果 In [30]: from functools import reduce In [31]: reduce(lambda a,b:a&b,map(dict.keys,[s1,s2,s3])) Out[31]: {'b'} #使得 from time import time from random import randint from collections import OrderedDict d=OrderedDict() players = list("ABCDEFGH") start=time() for i in range(8): input() p=players.pop(randint(0,8-i)) end=time() print(i+1,p,end-start) d[p]=(i+1,end-start) print('') print('-'*20) for k in d: print(k,d[k]) #查看用户历史记录功能,标准库collections的deque,双端循环队列,存在内容中,pickle存储到文件 from random import randint from collections import deque N = randint(0,100) history = deque([],5) def guess(K): if K ==N: print('正确') return True if K < N: print('%s is less-than N'%K) else: print("%s is greater-than N"%K) return False while True: line = input("请输入一个数字:") if line.isdigit(): k=int(line) history.append(k) if guess(k): break elif line =='history' or line =='h?': print(list(history))
可迭代对象和迭代器对象:
可迭代对象和迭代器对象 需求:从网络抓取每个城市的气温消息,显示 北京:15-20 黑龙江:3-10 上海13-19 一次抓取所有城市信息,会占很大的存储空间,现在想“用时访问”,吧所有城市气温封装到一个对象里,用for迭代 可迭代对象: In [1]: l=[1,2,3,4,5] In [2]: s='abcde' iter内置函数,可以得到一个迭代器对象 由可迭代对象,得到迭代器 iter(l) In [23]: type(l) Out[23]: list In [24]: type(iter(l)) Out[24]: list_iterator 可迭代对象都有__iter方法,可迭代接口 或者__getitem__序列接口 可迭代对象可以通过next()取值 In [26]: t=iter(l) In [27]: next(t) Out[27]: 1 In [28]: next(t) Out[28]: 2 In [29]: next(t) Out[29]: 3 In [30]: next(t) Out[30]: 4 In [31]: next(t) Out[31]: 5 In [32]: next(t) --------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-32-f843efe259be> in <module>() ----> 1 next(t) StopIteration:
读写取excel文件
Microsoft Excel是Microsoft为使用Windows和Apple Macintosh操作系统的计算机编写的一款电子表格软件。直观的界面、出色的计算功能和图表工具,再加上成功的市场营销,使Excel成为最流行的个人计算机数据处理软件。
import xlrd #打开excel文件,创建一个workbook对象,book对象也就是s11.xlsx文件,表含有sheet名 rbook=xlrd.open_workbook('/Users/yuchao/s11.xlsx') #sheets方法返回对象列表,[<xlrd.sheet.Sheet object at 0x103f147f0>] rbook.sheets() rsheet=rbook.sheet_by_index(0) #访问行数 rows=rsheet.nrows #访问列数 cols=rsheet.ncols print('行数:',rows,'列数',cols) #通过cell的位置坐标取得cell值 cell=rsheet.cell(0,0) print('0,0坐标的值是:',cell.value) #取得第二行的值,参数是(行数,起点,终点) row1=rsheet.row_values(1) print('第一行的值是:',row1)
# -*- coding:utf-8 -*- # Author : yuchao # Data : 2018/7/18 16:08 import xlrd, xlwt rbook = xlrd.open_workbook('/Users/yuchao/s11.xlsx') rsheet = rbook.sheet_by_index(0) # 取得sheet对象1 # 列数 nc = rsheet.ncols # 写入一条数据 rsheet.put_cell(0, nc, xlrd.XL_CELL_TEXT, '总分', None) # 遍历数据的行数 for row in range(1, rsheet.nrows): # 求和每一行数据 t = sum(rsheet.row_values(row, 1)) rsheet.put_cell(row, nc, xlrd.XL_CELL_NUMBER, t, None) #创建文档对象 wbook = xlwt.Workbook() wsheet = wbook.add_sheet(rsheet.name) #设置样式 style = xlwt.easyxf('align: vertical center, horizontal center') #遍历每一行 for r in range(rsheet.nrows): #每一列 for c in range(rsheet.ncols): wsheet.write(r,c,rsheet.cell_value(r,c),style) wbook.save('/Users/yuchao/s11_bak.xlsx')
import xlrd from xlrd.book import Book from xlrd.sheet import Sheet from xlrd.sheet import Cell workbook = xlrd.open_workbook('/Users/yuchao/s11.xlsx') sheet_names = workbook.sheet_names() # sheet = workbook.sheet_by_name('工作表1') sheet = workbook.sheet_by_index(1) # 循环Excel文件的所有行 for row in sheet.get_rows(): # 循环一行的所有列 for col in row: # 获取一个单元格中的值 print(col.value)
努力成为一个开发者
个人站点:www.pythonav.cn