学习Python艰难的方式#25

时间:2014-07-05 04:38:53

标签: python

通过以下内容,我有一个我认为尚未回答的问题(并未在课程中提及):

当我运行print_first_wordprint_last_word时,结果列表会通过.pop()进行更改 - 但是当我运行print_first_and_last函数时,列表保持不变已经完成了。由于print_first_and_last同时调用print_first_wordprint_last_word,每个都通过.pop()更改列表,为什么在运行print_first_and_last后列表未更改?

 def break_words(stuff):
    '''This function will break up words for us.'''
    stuff.split(' ')
    return stuff.split(' ')

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 last word in the sentence'''
    word = words.pop(-1)
    print word  



def print_first_and_last(sentence):
    '''Prints first and last words in the sentence.'''
    words=break_words(sentence)
    print_first_word(words)
    print_last_word(words)

2 个答案:

答案 0 :(得分:1)

print_first_and_last()的第一行是words = break_words(sentence)

此行将创建新对象!这个新对象将是一个包含句子中每个单词的列表。这个新的(有点临时的)对象将被print_first_word()print_last_word()更改。

如果我们更改print_first_and_last()以便打印更多信息,这可能更清楚:

def print_first_and_last(sentence):
    words = break_words(sentence)

    print sentence, words
    print_first_word(words)
    print sentence, words
    print_last_word(words)
    print sentence, words

答案 1 :(得分:1)

运行:

def print_first_and_last(sentence):
    '''Prints first and last words in the sentence.'''
    words=break_words(sentence)
    print words
    print_first_word(words)
    print words
    print_last_word(words)
    print words

print_first_and_last('This is the first test')

将输出:

['This', 'is', 'the', 'first', 'test']
This
['is', 'the', 'first', 'test']
test
['is', 'the', 'first']

正如您所看到的,列表words显然已被更改!