python3列表推導式
阿新 • • 發佈:2018-11-11
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)
多次列印的結果分別如下:
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/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)
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