Python: Pythonic

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chao2016/article/details/81906817

Pythonic:极具Python特色的Python代码,即明显区别于其它语言的写法的代码。

很多时候,使用Pythonic会提高Python程序的运行速度,对于Python这种脚本语言来说,它可能比逻辑本身更重要。

下面有一个简单的例子:

import time

start = time.time()

# 1 一般写法
arr = []
for i in range(100000):
    arr.append(i)

end1 = time.time()

# 2 Pythonic的写法
arr = [i for i in range(100000)]

end2 = time.time()

# Pythonic的写法有时比逻辑本身更重要
print("1 runtime = ", end1-start)  # 0.02s
print("2 runtime = ", end2-end1)  # 0.008s

输出结果如下:

1 runtime =  0.020305871963500977
2 runtime =  0.008398056030273438

猜你喜欢

转载自blog.csdn.net/chao2016/article/details/81906817
今日推荐