1列表推导效率比传统的for 循环+append要快
code测试如下:
#传统的循环
import datetime
time1 = datetime.datetime.now()
list1 = []
for i in range(100000):
if i%3==0:
list1.append(i)
time2 = datetime.datetime.now()
print('cost_time1:',time2-time1)
#列表推倒
time3 = datetime.datetime.now()
list2=[i for i in range(100000) if i%2==0]
time4 = datetime.datetime.now()
print('cost_time2:',time4-time3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
多次打印的结果分别如下:
cost_time1: 0:00:00.016241
cost_time2: 0:00:00.011513
cost_time1: 0:00:00.016279
cost_time2: 0:00:00.011368
cost_time1: 0:00:00.017235
cost_time2: 0:00:00.011611
1
2
3
4
5
6
可以看出列表推导式不仅简洁,而且速度快了1/3左右。
2两次zip方法可以恢复原状
for i in zip([1,2,3],[4,5,6]):
print(i)
(1, 4)
(2, 5)
(3, 6)
for i in zip(*zip([1,2,3],[4,5,6])):
print(i)
(1, 2, 3)
(4, 5, 6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
3带*的表达式可以获取序列的一部分
*a,b,c = 1,2,3,4,5
a
Out[8]: [1, 2, 3]
b
Out[9]: 4
c
Out[10]: 5
#同样的
a,*b,c=1,2,3,4,5
a
Out[12]: 1
b
Out[13]: [2, 3, 4]
c
Out[14]: 5
---------------------
【转载】仅作分享,侵删
作者:诺坎普奇迹
原文:https://blog.csdn.net/wangxingfan316/article/details/81155001
|
|