簡體   English   中英

Python速成課程8-10

[英]Python crash course 8-10

我目前正在閱讀Eric Matthes撰寫的Python速成課程,並做一些問題集。 其中之一給我一些困難,我希望有人可以幫助我。

8-9。 魔術師:列出魔術師的姓名。 將列表傳遞給一個名為show_magicians()的函數,該函數將打印列表中每個魔術師的姓名。

8-10。 偉大的魔術師:從練習8-9開始,復制程序。 編寫一個函數make_great(),通過在每個魔術師的名字前添加短語great來修改魔術師的列表。 調用show_magicians()以查看該列表實際上已被修改。

這就是我對於8-9的要求:

magician_names=['Alice', 'Alex', 'Blake']
def show_magicians(n):
    for magician in n:
        print (magician)

show_magicians(magician_names)

我只是真的不知道8-10會做什么

為此,您可以追加到字符串並重新分配以在每個元素的末尾添加單詞:

magician += " the great"

在這里, +=運算符附加一個字符串,然后重新分配,這等效於以下內容:

magician = magician + " the great"    

現在,您可以將其添加到如下函數中:

def make_great(list_magicians):
    for i in range(len(list_magicians)):
        list_magicians[i] += " the great"

make_great(magician_names)
show_magicians(magician_names)

輸出為:

Alice the great
Alex the great
Blake the great

這是如何工作的,我們使用了一個“計數器” for循環,類似於C語言(您也可以在此處使用enumerate )中的那個,通過使用下標循環遍歷每個元素。 然后,將字符串“ the great”附加到所有元素。


你之所以不能只是做一個簡單for-in循環和修改這些值是因為for-in副本中的變量的值之前in

for magician in list_magicians: # magician is a temporary variable, does not hold actual reference to real elements

如果它們沒有實際引用,則無法修改引用,因此需要使用計數器循環通過下標訪問實際引用的原因。

好的,您已經知道如何遍歷列表。 您想要做一個類似的功能,在這里您將引用我的magician的字符串修改為“ The Great”。

那么,如果您有一個字符串“ Smedley”,並且想要將其更改為字符串“ Smedley the Great”,您將如何做?

更新

因此,既然答案已經給出了,那么還有其他一些選項更“實用”並且可以說更安全,因為您可以免受別名等的影響。

選項1:創建一個新列表,例如:(這些示例是使用iPython完成的,這是一個非常方便的工具,值得安裝以學習Python)

def make_great_1(lst):
    rtn = []
    for m in lst:
        rtn.append(m+" the Great")
    return rtn

In [7]: mages = [ 'Gandalf', 'Mickey' ]

In [8]: make_great_1(mages)
Out[8]: ['Gandalf the Great', 'Mickey the Great']

選項2:使用列表理解:

In [9]: [ mg+" the Great" for mg in mages ]
Out[9]: ['Gandalf the Great', 'Mickey the Great']

現在,問題出在修改列表,很容易想象這意味着您應該修改字符串,但實際上Python(除非使用MutableString )無論如何都會產生一個副本。 如果您想真正變得挑剔,可以重新選擇這兩個選項之一,以將新列表分配給我的情況下的mages ,或者分配給您的magician_names

該問題要求您修改magician_names 由於在每個條目magician_namesstrstrs是不可修改的,你不能簡單地修改每個strmagician_names通過附加" the great"吧。 相反,您需要用其修改后的版本替換 magician_names每個str

因此,這種看似簡單的方法:

def make_great(l):
    for name in l:
        name += " the great"

make_great(magician_names)

不修改magician_names 它只是創建一個新的str對象,並將其分配給for loop本地的name變量。 magician_names每個元素都是不變的,即,它仍指向相同的str對象。

但是這種方法:

def make_great(l):
    for index, name in enumerate(l):
        l[index] = name + " the great"

make_great(magician_names)

更改magician_names指向的str對象,從而根據需要修改magician_names


根據您的評論,

for index in range(len(l)):
    name = l[index]
    l[index] = name + " the great"

只是Python的寫法:

 for index in range(len(l)): name = l[index] l[index] = name + " the great" 

enumerate(l)返回一個可迭代的(實際上是一個惰性生成器),它為l每個元素生成一個匹配的index, element對。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM