温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

写出优雅的python小技巧

发布时间:2020-08-03 11:58:46 来源:亿速云 阅读:176 作者:清晨 栏目:编程语言

这篇文章将为大家详细讲解有关写出优雅的python小技巧,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

在Python社区文化的浇灌下,演化出了一种独特的代码风格,去指导如何正确地使用Python,这就是常说的pythonic。一般说地道(idiomatic)的python代码,就是指这份代码很pythonic。pythonic的代码简练,明确,优雅,绝大部分时候执行效率高。阅读pythonic

的代码能体会到“代码是写给人看的,只是顺便让机器能运行”畅快。

那么如何写出优雅的python代码呢?下面的内容或许会对你有帮助

遍历一个范围内的数字

for i in [0, 1, 2, 3, 4, 5]:
    print i ** 2
for i in range(6):
    print i ** 2

更好的方法 

for i in xrange(6):
    print i ** 2

xrange会返回一个迭代器,用来一次一个值地遍历一个范围。这种方式会比range更省内存。xrange在Python 3中已经改名为range。

 遍历一个集合

colors = ['red', 'green', 'blue', 'yellow']
for i in range(len(colors)):
    print colors[i]

更好的方法

for color in colors:
    print color

反向遍历

colors = ['red', 'green', 'blue', 'yellow']
for i in range(len(colors)-1, -1, -1):
    print colors[i]

更好的方法

for color in reversed(colors):
    print color

遍历一个集合及其下标

 colors = ['red', 'green', 'blue', 'yellow']
 for i in range(len(colors)):
    print i, '--->', colors[i]

更好的方法

for i, color in enumerate(colors):
    print i, '--->', color

这种写法效率高,优雅,而且帮你省去亲自创建和自增下标。

当你发现你在操作集合的下标时,你很有可能在做错事。

遍历两个集合

names = ['raymond', 'rachel', 'matthew']
colors = ['red', 'green', 'blue', 'yellow']
n = min(len(names), len(colors))
for i in range(n):
    print names[i], '--->', colors[i]
 
for name, color in zip(names, colors):
    print name, '--->', color

更好的方法

 for name, color in izip(names, colors):
    print name, '--->', color

关于写出优雅的python小技巧就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI