艰难学Python,第25题,结果不如预期
我正在做《Learn Python the Hard Way》的第25个练习,但结果跟我预期的不一样。当我在命令行里调用 print_first_word
这个函数,并把参数 words
(这是一个列表)传进去时,我输入的是:
ex25.print_first_word(words)
我应该看到:
All
但是,我看到的是:
wait.
值得一提的是,words
的内容是:
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
这是我的代码:
def break_words(stuff):
"""This Function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print word
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print word
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence"""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
4 个回答
问题在于我没有导入我以为的那个文件。在“艰难的Python学习,练习25,模块没有属性'print_last_word'”这个问题下,有人给我建议,
print ex25.__file__
这让我看到了我实际上导入的文件。然后,我确保从正确的路径导入。
如果这样更新我的问题更好,请告诉我。谢谢!
有两件事你需要记住。首先,pop()
这个方法会改变你用它操作的列表;一旦你用pop()
取出一个项目,它就不再在列表里了。看看下面这段命令:
>>> words = ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
>>> words.pop(0)
'All'
>>> words.pop(0)
'good'
>>> words.pop(0)
'things'
>>> words.pop(0)
'come'
>>> words.pop(0)
'to'
>>> words.pop(0)
'those'
>>> words.pop(0)
'who'
>>> words.pop(0)
'wait.'
>>> words.pop(0)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
words.pop(0)
IndexError: pop from empty list
>>>
第二点,这个可能有点让人困惑,列表是通过引用传递的。这是什么意思呢?就是当你调用print_first_word(words)
时,words.pop(0)
不仅仅是在你的函数内部修改一个局部变量,它实际上是在修改你原来的列表!所以,如果你多次调用print_first_word(words)
,每次的输出都会不同,就像你上面看到的那样。
你可以通过使用word = words[0]
来解决这个问题,这样只是获取索引为0的值,而不是用word = words.pop(0)
去修改列表。
就像我说的,我没有改动你代码中的任何一个字符,它运行得非常好。这里是我写的代码:
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0)
print word
words=['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
print_first_word(words)
结果是 All
我猜你是在IDLE(或者其他交互式命令行工具)里操作的,而你之前的“测试运行”可能影响了你的输入。先试着用print
打印一下words
,看看它是不是你想要的样子。你的代码看起来是对的。
记住,list.pop
(就像你在函数print_first_word(words)
里用的)实际上是把目标从列表中移除。也就是说:
words = ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
words.pop(0) # returns 'All', but since I don't assign it anywhere, who cares
print(words)
# ['good', 'things', 'come', 'to', 'those', 'who', 'wait.']
如果你并不想从列表中删除一个元素,就不要用pop
,直接用切片就可以了。
words = ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
words[0] # ALSO returns 'All', though again I'm not doing anything with it
print(words)
# ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']