[Python高效编程]
来源:互联网 发布:淘宝返利机器人怎么做 编辑:程序博客网 时间:2024/05/22 13:55
开发环境
- Python版本: python3.6
- 调试工具:pycharm 2017.1.3
- 电脑系统:Windows 10 64位系统
对于不同的数据结构:列表,字典,集合,通用的数据筛选手段为迭代
例如筛选data中的字符串:
data = [1, 2, 'a', -3, 'b', -4, 5, 5, 'c', -7]res = []for x in data: if isinstance(x, str): res.append(x)print(res)
['a', 'b', 'c']
为了使编程风格更加地pythonic,采用函数式编程。
列表,过滤掉列表中的数值
使用filter函数
data = [1, 2, 'a', -3, 'b', -4, 5, 5, 'c', -7]res = filter(lambda x: isinstance(x, str), data)print(res)print(list(res))
<filter object at 0x00000204B7AE63C8>['a', 'b', 'c']
使用列表解析
data = [1, 2, 'a', -3, 'b', -4, 5, 5, 'c', -7]res = [x for x in data if isinstance(x, str)]print(res)
['a', 'b', 'c']
推荐使用列表解析,处理速度更快
字典,筛选出字典中值大于80的项
step1:随机生成某班10人的学号和分数
step2:筛选分数大于80的键值对k,v
from random import randintdata = {}data = {x: randint(60, 100) for x in range(1, 11)}print(data)res = {}res = {key: value for key, value in data.items() if value > 80}print(res)
{1: 61, 2: 69, 3: 83, 4: 94, 5: 72, 6: 65, 7: 94, 8: 100, 9: 74, 10: 92}{3: 83, 4: 94, 7: 94, 8: 100, 10: 92}
集合,筛选集合中偶数的元素
step1:将data转化为集合
step2:集合解析,对2取模为0
from random import randintdata = []data = [randint(1, 100) for _ in range(1, 11)]print(data)s = set(data)print(s)res = set()res = {x for x in s if x%2 == 0}print(res)
[43, 13, 3, 100, 62, 89, 17, 37, 66, 70]{66, 3, 100, 37, 70, 43, 13, 17, 89, 62}{62, 66, 100, 70}
小结:列举了列表,字典,集合中根据条件筛选数据的方法,用列表解析和filter函数的速度都远快于迭代方式。
阅读全文
0 0
- Python高效编程技巧
- Python高效编程技巧
- Python高效编程技巧
- Python高效编程技巧
- Python高效编程技巧
- python高效编程
- Python高效编程技巧
- Python高效编程技巧
- python 高效编程
- Python高效编程技巧
- Python高效编程技巧
- Python高效编程技巧
- [Python高效编程]
- [Python高效编程]
- [Python高效编程]
- [Python高效编程]
- [Python高效编程]
- [Python高效编程]
- API接口签名验证
- 【Spring+SpringMVC+Mybatis】利用SSM整合,完成用户登录、注册、修改密码系统
- 基于分布式环境下限流系统的设计
- hadoop
- JAVA中的volatile
- [Python高效编程]
- python strip()函数和Split函数的用法总结
- 游戏:数字对对碰
- Servlet分页技术
- 51Nod 1183 编辑距离
- 使用PHP生成二维码的两种方法(带logo图像)
- 【BZOJ2175】旅游(树链剖分,Link-Cut Tree)
- 自定义网络框架之json文本请求
- JVM体系结构认知