pythonic是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25011078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does pythonic mean?
提问by Jon
On many websites I often see comments that code isn't pythonic, or that there is a more pythonic way to achieve the same goal.
在许多网站上,我经常看到评论说代码不是 Pythonic,或者有更 Pythonic 的方式来实现相同的目标。
What does pythonic mean in this context? For example, why is
在这种情况下,pythonic 是什么意思?例如,为什么
while i < someValue:
do_something(list[i])
i += 1
not pythonic while
不是pythonic而
for x in list:
doSomething(x)
is pythonic?
是蟒蛇吗?
采纳答案by James
Exploiting the features of the Python language to produce code that is clear, concise and maintainable.
利用 Python 语言的特性来生成清晰、简洁和可维护的代码。
Pythonic means code that doesn't just get the syntax right but that follows the conventions of the Python community and uses the language in the way it is intended to be used.
Pythonic 意味着代码不仅语法正确,而且遵循 Python 社区的约定,并以预期使用的方式使用语言。
This is maybe easiest to explain by negative example, as in the linked article from the other answers. Examples of unpythonic code often come from users of other languages, who instead of learning a Python programming patterns such as list comprehensions or generator expressions, attempt to crowbar in patterns more commonly used in C or java. Loops are particularly common examples of this.
这可能最容易用反面例子来解释,就像其他答案中的链接文章一样。非pythonic 代码的例子通常来自其他语言的用户,他们不是学习 Python 编程模式,如列表推导式或生成器表达式,而是尝试使用 C 或 java 中更常用的模式。循环是这方面特别常见的例子。
For example in Java I might use
例如在 Java 中我可能会使用
for i in (i; i < items.length ; i++)
{
n = items[i];
... now do something
}
In Python we can try and replicate this using while loops but it would be cleaner to use
在 Python 中,我们可以尝试使用 while 循环来复制它,但使用起来会更干净
for i in items:
i.perform_action()
Or, even a generator expression
或者,甚至是一个生成器表达式
(i.some_attribute for i in items)
So essentially when someone says something is unpythonic, they are saying that the code could be re-written in a way that is a better fit for pythons coding style.
所以本质上,当有人说某些东西不是 Pythonic 时,他们是在说可以以更适合 Python 编码风格的方式重写代码。
Typing import thisat the command line gives a summary of Python principles. Less well known is that the source code for import thisis decidedly, and by design, unpythonic! Take a look at it for an example of what not to do.
import this在命令行中键入会给出 Python 原理的摘要。鲜为人知的是,它的源代码import this绝对是设计的,非pythonic!看一看它是什么不该做的例子。

