Python培训之如何写出优雅的python

发布时间:2022-08-09 09:40:34 人气:123 作者:多测师

  在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

Python培训之如何写出优雅的python

  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培训之如何写出优雅的python,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/


返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线