我做了以下兩個功能:
def make_great(magicians):
for i in range(len(magicians)):
magicians[i] = " the Great."
def show_magicians(magicians):
for magician in magicians:
print(magician)
然后我將魔術師串列的副本傳遞給 make_great 函式,將其分配給 copy 變數,并將其傳遞給 show_magicians 函式:
magicians = ['Peter', 'Hendrick', 'Charles', 'Ryan', 'Alex']
copy = make_great(magicians[:])
show_magicians(copy)
這給了我 TypeError: 'NoneType' object is not iterable。
當我將原始串列傳遞給它時,它會起作用。但是,我也嘗試了以下方法:
magicians = ['Peter', 'Hendrick', 'Charles', 'Ryan', 'Alex']
print(make_great(magicians))
make_great(magicians)
show_magicians(magicians)
這給出了所需的結果,但 print 函式也回傳一個 None 物件。我有兩個問題:1)為什么我只在串列副本中得到 TypeError,以及 2)為什么 make_great 函式在兩種情況下都回傳 None 物件(副本和原始串列)?
uj5u.com熱心網友回復:
您的make_great()函式回傳None,因為它沒有return陳述句。
它無用地更新其本地副本magicians,然后在函式結束時超出范圍而丟失。您需要回傳magicians串列。
uj5u.com熱心網友回復:
make_great(magicians) 需要從函式回傳。
“當我將原始串列傳遞給它時,它就起作用了。” 這是因為魔術師是可變的。make_great(magicians) 更改了串列中的每個元素。
def make_great(magicians):
for i in range(len(magicians)):
magicians[i] = " the Great."
return magicians
def show_magicians(magicians):
for magician in magicians:
print(magician)
magicians = ['Peter', 'Hendrick', 'Charles', 'Ryan', 'Alex']
copy = magicians[:]
print(f'{copy=}') # Verify copy is not equal to None
show_magicians(make_great(copy))
print(f'{copy=}') # Demonstrate make_great mutated the list copy
輸出
copy=['Peter', 'Hendrick', 'Charles', 'Ryan', 'Alex']
Peter the Great.
Hendrick the Great.
Charles the Great.
Ryan the Great.
Alex the Great.
copy=['Peter the Great.', 'Hendrick the Great.', 'Charles the Great.', 'Ryan the Great.', 'Alex the Great.']
uj5u.com熱心網友回復:
如果make_great更改了它的引數,呼叫者有責任維護對該串列的參考,而不是make_great回傳對它的參考。
magicians = ['Peter', 'Hendrick', 'Charles', 'Ryan', 'Alex']
copy = magicians[:]
make_great(copy)
show_magicians(magicians)
如果make_great將制作一個副本,它應該保持原始串列不變并回傳對修改后副本的參考。
def make_great(magicians):
return [x "the Great." for x in magicians]
copy = make_great(magicians)
show_magicians(copy)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/434865.html
