3 回答

TA贡献2011条经验 获得超2个赞
您编写 for 循环的方式是问题所在。至于 for 循环从列表中获取一个元素并将该值传递到块内,并为下一个元素重复相同的操作。
for magician in mag_names:
这里的魔术师从 mag_names 开始有一个值,在你的情况下它是 'houdini' 你不应该再次在你的 for 循环中弹出 mag_names。所以'for'循环的正确代码将是这样的
for magician in mag_names:
full_name = magician
printed_list.append(full_name.title())
您对 while 循环的实现工作正常,因为 while 的工作方式不同。只要条件为真,它就会执行块。所以 while mag_names:
将评估为True
直到项目为空。当它们在您的代码中一一弹出时,列表会缩小并最终变为空并计算为False
for 循环和 while 循环实现输出反转的原因现在对您来说应该是显而易见的。

TA贡献1836条经验 获得超4个赞
while循环不像循环那样跟踪索引本身for。
while loop: 它只是检查mag_names非空,它将继续循环。由于元素弹出,您的列表在某一时间点变为空。因此你结束了循环。While 循环不会自行迭代到下一个元素。
for loop: For 循环在每次迭代中递增到下一个元素。在您的情况下,您还弹出每个元素中的元素,因此每次迭代中列表大小减少 2,因此您不会得到与 while 循环相同的结果
您的代码的问题是您使用相同的列表进行迭代和弹出元素。因此,在每次迭代中,索引前进 1,同时弹出最后一个元素。
解决方案是mag_names在迭代过程中使用一个新的副本[:]
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贡献1862条经验 获得超6个赞
让我们通过使用append然后使用printed_list[:] = []清空列表来简化代码,而不是编写一些复杂的代码。这是代码:
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)
我调整了你的一些代码,使其工作。希望能帮助到你 :)
添加回答
举报