艰苦地学习Python

艰苦地学习Python,python,Python,通过下面的内容,我有一个我认为尚未回答的问题(在本课中也没有提到): 当我运行print\u first\u word或print\u last\u word时,生成的列表会通过.pop()进行更改-然而,当我运行print\u first\u和\u last功能时,列表在完成后保持不变。既然print\u first\u和\u last同时调用print\u first\u word和print\u last\u word,它们都通过.pop()更改列表,为什么运行print\u first\

通过下面的内容,我有一个我认为尚未回答的问题(在本课中也没有提到):

当我运行
print\u first\u word
print\u last\u word
时,生成的列表会通过
.pop()
进行更改-然而,当我运行
print\u first\u和\u last
功能时,列表在完成后保持不变。既然
print\u first\u和\u last
同时调用
print\u first\u word
print\u last\u word
,它们都通过
.pop()
更改列表,为什么运行
print\u first\u和\u 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)

print\u first\u and\u last()
的第一行是
words=break\u单词(句子)

此行将创建一个新对象!这个新对象将是一个包含句子中每个单词的列表。这个新的(有些临时的)对象将被
print\u first\u word()
print\u last\u word()
更改

如果我们更改了
print\u first\u和\u 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
运行:

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']

正如您所看到的,列表
单词
显然已更改

字符串是通过值传递的(因此创建了一个新副本),而列表是通过引用传递到函数中的。在您的示例中,如果调用
print\u first\u和\u last
,则该句子将不会被修改,因为创建了该句子的新副本。另一方面,如果您将列表传递给
print\u first\u和\u last
,它将被修改。@dparpyani:在python中,所有内容都是通过引用传递的。。。某些对象只是提供了一个不可变的接口。您能否给出一个您将调用
print\u first\u和\u last()
的输入示例,以及您发现令人惊讶的具体输出如何?@sharth-假设我通过变量语句将字符串“Today I will to the store”传递到函数中(语句=“今天我将去存储”)。函数将返回今天并存储,这是我所期望的,但当我检查现在包含的句子时,它是不变的。这与运行print\u first\u word(首先需要在变量句子上运行break\u words将字符串转换为列表)形成对比由于此函数将通过pop(0)删除字符串的第一部分,因此当我运行后看到句子包含的内容时,句子包含“我去商店"空间不足-但基本上我想说的是,既然
print\u first\u和\u last
都调用
print\u first\u word
print\u last\u word
,它们都通过
.pop
来更改列表,我直觉上觉得
print\u first\u和\u last
会保持列表不变回答和阿尔法辛很有帮助,谢谢。我想我在概念化全局与局部时遇到了困难,所以你实际上是复制了我的答案,并扩展了你的两句话。“那太差劲了……”阿尔法辛:我们差不多是在同一时间写的。