python的推导式是用于快速处理数据的方法。

主要有:列表推导式、集合推导式和字典推导式

import time
import numpy as np

列表推导式:

1. 速度快

t1 = time.time()
aa = [ii for ii in range(1000000) if ii % 2 ==0] # 取出偶数
#print(aa)
t2 = time.time()
print('总共耗时为:' + str(t2 - t1) + ' 秒') # 总共耗时为:0.07380175590515137 秒

当直接使用for循环时:

t3 = time.time()
bb = []
for ii in range(1000000):
if ii % 2 ==0:
bb.append(ii)
#print(bb)
t4 = time.time()
print('总共耗时为:' + str(t4 - t3) + ' 秒') # 总共耗时为:0.12566447257995605 秒

2. 嵌套多层for语句

np_tmp = np.ones((10000,10000))
t5 = time.time()
#cc = [jj for ss in np_tmp for jj in ss]
cc = [ # 写成这种形式看上去更直观
jj
for ss in np_tmp
for jj in ss
]
t6 = time.time()
print('总共耗时为:' + str(t6 - t5) + ' 秒') # 总共耗时为:7.131944894790649 秒

直接使用for:

t7 = time.time()
dd = []
for ss in np_tmp:
for jj in ss:
dd.append(jj)
t8 = time.time()
print('总共耗时为:' + str(t8 - t7) + ' 秒') # 总共耗时为:14.19404673576355 秒

生成器:

# 生成器,将上述的[]改成()即可实现
gene_ = (i for i in range(30) if i % 2 is 0)
print(list(gene_)) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
print(gene_) # <generator object <genexpr> at 0x000001FEF348C5E8>

字典推导式,可用于快速改变字典形式:

ee = {'大贤':100, '大蘅':80, '离':50, '默':40}
for ii,dict_ in enumerate(ee.items()):
print(ii)
print(dict_[0], dict_[1])
ee_1 = {key: value+100 for key, value in ee.items()}
print(ee_1) # {'大贤': 200, '大蘅': 180, '离': 150, '默': 140}
ee_2 = {ii: {dict_[0]:dict_[1]+100} for ii,dict_ in enumerate(ee.items())}
print(ee_2) # {0: {'大贤': 200}, 1: {'大蘅': 180}, 2: {'离': 150}, 3: {'默': 140}}

集合推导式(快速产生集合):

ff = '你是不是来这里买东西的?买啥?'
set_ = {w for w in ff} # type(set_) is: set
print(set_) # 集合(会去掉重复值):{'?', '来', '的', '你', '啥', '这', '不', '里', '西', '买', '是', '东'}

参考:

https://www.cnblogs.com/tkqasn/p/5977653.html

https://www.cnblogs.com/amiza/p/10159293.html

最新文章

  1. WebAPI IIS PUT和DELETE请求失败 405
  2. 使用Python解析JSON数据的基本方法
  3. centos6虚拟机复制后修改网卡
  4. Ajax原生写法
  5. 找出数组中最长的连续数字序列(JavaScript实现)
  6. org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
  7. Azure中的分布式1——多实例
  8. Aspose.word总结
  9. 字符串格式化 String.format() 案例
  10. sublime2/3自总结经常使用快捷键(2的居多)
  11. [git] fatal: This operation must be run in a work tree
  12. 2.从AbstractQueuedSynchronizer(AQS)说起(1)——独占模式的锁获取与释放
  13. prometheus client_golang使用
  14. 2017 .NET 開發者須知
  15. Java获取当日的起始时间,结束时间,现在时间,是否在时间段中。
  16. LVS(五)LVS的持久连接
  17. office全系列激活脚本-改良版.cmd
  18. js赋值后,不影响源变量的方法。
  19. Web.Debug.config和Web.Release.config设置xdt:Transform无效的解决办法
  20. 谈谈ISCSI\NAS\SAN及SAS之间的区别及优缺点--待补充

热门文章

  1. JDK8:Lambda根据 单个字段、多个字段,分组求和
  2. Caused by java.lang.Exception Failed to send data to Kafka Expiring
  3. Dockerfile常用指令说明
  4. 史上最全的中高级Java面试题汇总
  5. Git 更新
  6. Python之路【第九篇】:Python面向对象
  7. Go基础编程实践(三)—— 日期和时间
  8. pytest_04_测试用例setup和teardown
  9. liunx下Oracle安装
  10. JAVA-AbstractQueuedSynchronizer-AQS