3 回答

TA貢獻(xiàn)2011條經(jīng)驗(yàn) 獲得超2個(gè)贊
您編寫(xiě) for 循環(huán)的方式是問(wèn)題所在。至于 for 循環(huán)從列表中獲取一個(gè)元素并將該值傳遞到塊內(nèi),并為下一個(gè)元素重復(fù)相同的操作。
for magician in mag_names:
這里的魔術(shù)師從 mag_names 開(kāi)始有一個(gè)值,在你的情況下它是 'houdini' 你不應(yīng)該再次在你的 for 循環(huán)中彈出 mag_names。所以'for'循環(huán)的正確代碼將是這樣的
for magician in mag_names:
full_name = magician
printed_list.append(full_name.title())
您對(duì) while 循環(huán)的實(shí)現(xiàn)工作正常,因?yàn)?while 的工作方式不同。只要條件為真,它就會(huì)執(zhí)行塊。所以 while mag_names:
將評(píng)估為True
直到項(xiàng)目為空。當(dāng)它們?cè)谀拇a中一一彈出時(shí),列表會(huì)縮小并最終變?yōu)榭詹⒂?jì)算為False
for 循環(huán)和 while 循環(huán)實(shí)現(xiàn)輸出反轉(zhuǎn)的原因現(xiàn)在對(duì)您來(lái)說(shuō)應(yīng)該是顯而易見(jiàn)的。

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
while循環(huán)不像循環(huán)那樣跟蹤索引本身for。
while loop: 它只是檢查mag_names非空,它將繼續(xù)循環(huán)。由于元素彈出,您的列表在某一時(shí)間點(diǎn)變?yōu)榭?。因此你結(jié)束了循環(huán)。While 循環(huán)不會(huì)自行迭代到下一個(gè)元素。
for loop: For 循環(huán)在每次迭代中遞增到下一個(gè)元素。在您的情況下,您還彈出每個(gè)元素中的元素,因此每次迭代中列表大小減少 2,因此您不會(huì)得到與 while 循環(huán)相同的結(jié)果
您的代碼的問(wèn)題是您使用相同的列表進(jìn)行迭代和彈出元素。因此,在每次迭代中,索引前進(jìn) 1,同時(shí)彈出最后一個(gè)元素。
解決方案是mag_names在迭代過(guò)程中使用一個(gè)新的副本[:]
def show_magicians(mag_names):
print("Here is the name of the magicians")
print("The old list is :", mag_names)
for magician in mag_names[:]:
full_name = mag_names.pop()
printed_list.append(full_name.title())
print("The name of the magician is ", full_name.title())
print("The old list now :", mag_names)
print("The new list is :", printed_list)
magicians = ['houdini', 'williams', 'sunderland']
printed_list = []
show_magicians(magicians)

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
讓我們通過(guò)使用append然后使用printed_list[:] = []清空列表來(lái)簡(jiǎn)化代碼,而不是編寫(xiě)一些復(fù)雜的代碼。這是代碼:
def show_magicians(magicians):
print("Here is the name of the magicians")
print("The old list is :",magicians)
while magicians:
full_name = magicians.pop()
printed_list.append(full_name.title())
print("The name of the magician is ",full_name.title())
print("The old list now :",magicians)
print("The new list is :",printed_list)
print("***********With for loop******************")
for magician in printed_list:
printed_list_new.append(magician)
print("The name of the magician is ", magician)
printed_list[:] = []
print("The old list now:", printed_list)
print("The new list now:", printed_list_new)
magicians = ['houdini', 'williams', 'sunderland']
printed_list = []
printed_list_new = []
show_magicians(magicians)
我調(diào)整了你的一些代碼,使其工作。希望能幫助到你 :)
添加回答
舉報(bào)