在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]
推荐学习《python教程》
更好的方法
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
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 模板不会安装或需要功能定制以及二次开发?
发表评论
还没有评论,快来抢沙发吧!