如果你谷歌搜索“pythonic”,你会发现the same three examples。这里有很多关于stackoverflow的问题,询问如何以 pythonoic 的方式完成这个和那个,所以一些不错的pythonic代码示例的集合会很好!
答案 0 :(得分:5)
Pythonic是对最具惯用语Python代码的描述。这不仅意味着代码对其他程序员来说很容易理解,而且通常也是使用Python的最有效方式。
答案 1 :(得分: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!
答案 2 :(得分:2)
这个问题要求收集一些pythonic代码,所以我会添加一些我喜欢的代码因为他们使用强大的 pythonic 运算符*
和**
:< / p>
使用解包运算符转换*
解包操作符是一个非常强大的工具,允许我们“解压缩”列表。我不知道其他语言的等价物。
这个操作符可以有非常有趣和有用的应用程序:
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}
答案 3 :(得分:0)
“Pythonic”仅仅意味着遵循常见的Python习语。
只需按照禅宗的Python :