访问子字符串
2015-10-22 10:46
344 查看
切片是个好方法,但是它一次只能取得一个字段;如果还考虑字段的长度,struct.unpack可能更适合。
利用缓存的方法:
import struct def fields(baseformat, theline, lastfield=False): # theline超出的长度也由这个base-format确定 # (通过struct.calcsize计算确切的长度) numremain = len(theline) - struct.calcsize(baseformat) # 用合适的s或x字段完成格式,然后unpack format = "%s %d%s" % (baseformat, numremain, lastfield and "s" or "x") return struct.unpack(format, theline)
利用缓存的方法:
import struct def fields(baseformat, theline, lastfield=False, _cache={}): # 生成键并尝试获得缓存的格式字符串 key = baseformat, len(theline), lastfield format = _cache.get(key) if format is None: # 没有缓存的格式字符串,创建并缓存之 numremain = len(theline) - struct.calcsize(baseformat) _cache[key] = format = "%s %d%s" % (baseformat, numremain, lastfield and "s" or "x") return struct.unpack(format, theline)
相关文章推荐
- 数字字体
- Docker系列(四)Dockerfile
- 根据现有IP地址获取其地理位置(省份,城市等)的方法
- IOS- 如何集成支付宝
- row_number() over(partition by 列名1 order by 列名2 desc1) as rank
- Meta http-equiv属性详解(转)
- 【SCOI 2009】生日快乐 DFS
- 阅读Face Alignment by Explicit Shape Regression
- POJ 1658
- AI3D立体字
- 第13章 类继承 --抽象基类
- 使用EntityFramework的烦恼
- Light OJ 1011 - Marriage Ceremonies(状压DP)
- 弹出层被FLASH遮挡解决办法(ckplayer解决)
- jquery 实现tab选项卡功能
- 淘宝刘昆:阿里数据库架构变迁与展望
- Qt Enterprise v5.5.1正式发布[附下载]
- DELPHI 线程池
- android MTK驱动背光唤醒流程
- 简单三步-实现dede站内搜索功能