• 技术文章 >常见问题 >Python常见问题

    如何写出优雅的python

    silencementsilencement2019-12-09 10:06:13原创2266

    在Python社区文化的浇灌下,演化出了一种独特的代码风格,去指导如何正确地使用Python,这就是常说的pythonic。一般说地道

    (idiomatic)的python代码,就是指这份代码很pythonic。pythonic的代码简练,明确,优雅,绝大部分时候执行效率高。阅读pythonic

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

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

    遍历一个范围内的数字

    1

    2

    3

    4

    for i in [0, 1, 2, 3, 4, 5]:

        print i ** 2

    for i in range(6):

        print i ** 2

    更好的方法

    1

    2

    for i in xrange(6):

        print i ** 2

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

    遍历一个集合

    1

    2

    3

    colors = ['red', 'green', 'blue', 'yellow']

    for i in range(len(colors)):

        print colors[i]

    推荐学习《python教程

    更好的方法

    1

    2

    for color in colors:

        print color

    反向遍历

    1

    2

    3

    colors = ['red', 'green', 'blue', 'yellow']

    for i in range(len(colors)-1, -1, -1):

        print colors[i]

    更好的方法

    1

    2

    for color in reversed(colors):

        print color

    遍历一个集合及其下标

    1

    2

    3

    colors = ['red', 'green', 'blue', 'yellow']

    for i in range(len(colors)):

       print i, '--->', colors[i]

    更好的方法

    1

    2

    for i, color in enumerate(colors):

        print i, '--->', color

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

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

    遍历两个集合

    1

    2

    3

    4

    5

    6

    7

    8

    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

    更好的方法

    1

    2

    for name, color in izip(names, colors):

       print name, '--->', color

    专题推荐:代码规范
    上一篇:如何在linux下运行python 下一篇:如何用python判定是否为闰年

    相关文章推荐

    • 一文读懂Python代码的书写规范• 零基础学python之迭代器

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网