python的推导式 —— 列表推导式、集合和字典推导式

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

猜你喜欢

转载自www.cnblogs.com/qi-yuan-008/p/12075114.html