【问题标题】:What practices would you consider "pythonic"? [closed]你会认为哪些做法是“pythonic”? [关闭]
【发布时间】:2010-10-15 13:55:36
【问题描述】:

如果您在 Google 上搜索“pythonic”,您通常会找到 the same three examples。这里有很多关于 stackoverflow 的问题,询问如何以 pythonoic 方式完成这个和那个,所以收集一些不错的 pythonic 代码示例会很好!

【问题讨论】:

  • 投票结束:这里没有真正的问题。
  • 如果它是可读的并且产生预期的输出,它是Pythonic。

标签: python


【解决方案1】:

正如我在tag description 中所写:

Pythonic 是对最惯用的Python 代码的描述。这不仅意味着代码易于其他程序员理解,而且通常也是使用 Python 最有效的方式。

【讨论】:

    【解决方案2】:
    >>> import this
    The Zen of Python, by Tim Peters
    
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!
    

    【讨论】:

      【解决方案3】:

      该问题要求收集 pythonic 代码,因此我将添加一些我喜欢的代码,因为它们使用强大的 pythonic 运算符 ***

      转置使用解包运算符*

      解包操作符是一个非常强大的工具,它允许我们“解包”一个列表。我不知道其他语言中的任何等价物。

      这个运算符可以有非常有趣和有用的应用:

      a = [[1,2],[3,4]]
      a_transpose = zip(*a)
      

      使用元组解包运算符**进行字典连接

      再一次,我不知道其他语言的任何对应物。和上面一样,我们可以用这个操作符做很多事情,包括字典连接:

      a = {1:2,2:2}
      b = {2:37,3:42}
      a = dict(a,**b) # a is now {1:2,2:37,3:42}
      

      【讨论】:

        【解决方案4】:

        “Pythonic”只是意味着遵循常见的 Python 习语。

        只需遵循 Python 之禅

        • 美胜于丑。
        • 显式优于隐式。
        • 简单胜于复杂。
        • 复杂胜于复杂。
        • 平面优于嵌套。
        • 稀疏优于密集。
        • 可读性很重要。
        • 特殊情况不足以打破规则。
        • 虽然实用胜过纯粹。
        • 错误绝不应该悄无声息地过去。
        • 除非明确静音。
        • 面对模棱两可,拒绝猜测的诱惑。
        • 应该有一种——最好只有一种——明显的方法。
        • 虽然这种方式一开始可能并不明显,除非您是荷兰人。
        • 现在总比没有好。
        • 虽然从来没有比现在更好。
        • 如果实现难以解释,那就是个坏主意。
        • 如果实现易于解释,那可能是个好主意。
        • 命名空间是一个非常棒的想法——让我们做更多这样的事情!

        【讨论】:

          猜你喜欢
          • 2020-06-20
          • 2014-07-26
          • 2010-10-10
          • 2010-09-26
          • 2010-10-31
          • 1970-01-01
          • 2012-11-25
          • 2010-09-06
          • 2012-08-24
          相关资源
          最近更新 更多