python - 艰难地学习 Python Ex 25 : local variable/object assignment in functions

标签 python python-2.7

我正在通过学​​习 Zed Shaw 的书《Learn Python The Hard Way》来学习 python2 的基础知识。在练习 25 中,作者给出了一些函数,例如:

def break_words(sentence):
    words = sentence.split(' ')
    return words

def print_first_word(words):
    word = words.pop(0)
    print word

我像这样缩短了函数:

def break_words(sentence):
    return sentence.split(' ')

def print_first_word(sentence)
    print break_words(sentence).pop(0)

想知道作者将 .split() 和 .pop() 分配给words/word 是否有原因?

谢谢

最佳答案

我认为唯一的原因是可读性(在他们看来)。

对于许多人来说,直接返回它们也同样清楚,但这取决于编写代码的人或代码的编写对象。

我个人会采用您缩短它们的方法,但这是一个偏好问题。

接受 the ZEN of Python 的指导:

The Zen of Python 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!

作为旁注,有一个复活节彩蛋,可以通过运行导入此将其打印到控制台。

关于python - 艰难地学习 Python Ex 25 : local variable/object assignment in functions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47000122/

相关文章:

python - 如果不工作

python - 通过 DFs 列上的条件将权重列添加到 pandas DF

python - 使用 ttk.Notebook 小部件从右到左对齐选项卡

python - 查找两个非常大的列表之间的差异

python - 将大型 csv 文件从 NodeJS 发送到 python

python - Scrapy 似乎已安装但在 python shell 中时无法导入

通过谷歌模块的 Python 搜索给出 SSL : CERTIFICATE_VERIFY_FAILED Error

python - 使用 python 识别列表中元组长度为 0 的最佳方法是什么

python - 遍历列表返回负索引

python - 类格式问题