pythonic是什么意思? [英] What does pythonic mean?

查看:50
本文介绍了pythonic是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多网站上,我经常看到评论说代码不是 Pythonic,或者有更 Pythonic 的方式来实现相同的目标.

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 在这种情况下是什么意思?例如,为什么是

What does pythonic mean in this context? For example, why is

while i < someValue:
   do_something(list[i])
   i += 1

不是pythonic而

not pythonic while

for x in list:
   doSomething(x)

是蟒蛇吗?

推荐答案

利用 Python 语言的特性来生成清晰、简洁和可维护的代码.

Exploiting the features of the Python language to produce code that is clear, concise and maintainable.

Pythonic 意味着代码不仅语法正确,而且遵循 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 编程模式,如列表推导式或生成器表达式,而是尝试在 C 或 java 中更常用的模式中使用 Crowbar.循环是特别常见的例子.

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.

例如在 Java 中我可能会使用

For example in Java I might use

for(int index=0; index < items.length; index++) {
     items[index].performAction();
}

在 Python 中,我们可以尝试使用 while 循环来复制它,但使用起来会更干净

In Python we can try and replicate this using while loops but it would be cleaner to use

for item in items:
  item.perform_action()

或者,甚至是一个生成器表达式

Or, even a generator expression

(item.some_attribute for item in items)

所以本质上,当有人说某些东西不是 Pythonic 时,他们是说可以以更适合 Python 编码风格的方式重写代码.

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.

在命令行输入 import this 给出了 Python 原理的总结.鲜为人知的是,import this 的源代码绝对是设计的,非pythonic!看看它的一个例子,看看什么是不应该做的.

Typing import this at the command line gives a summary of Python principles. Less well known is that the source code for import this is decidedly, and by design, unpythonic! Take a look at it for an example of what not to do.

这篇关于pythonic是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆