英俊男孩建坤 发表于 2020-9-27 00:38:56

求大佬帮我瞅瞅我快哭了

guests = ['a','b','c']
print (guests)
print ("hello "+guests+" welcome")
guests="d"
print (guests)
#
print ("b can not attend.")
guests.append('e')
#
print(guests)
print("welcome "+guests+" attend my this party!")
print("welcome "+guests+" attend my this party!")
print("welcome "+guests+" attend my this party!")
print("welcome "+guests+" attend my this party!")
print("i find a big table,so we change the place")
guests.insert(0,'f')
#
guests.insert(2,'g')
#
print(guests)
print('i am so sorry ,i only can invite two.')
first = guests.pop(0)
print ("sorry "+guests.pop(0))
#sorry f
second = guests.pop(1)
print ("sorry "+guests.pop(1))
#sorry a
third = guests.pop(2)
print ("sorry "+guests.pop(2))
#sorry g
forth = guests.pop(3)
print ("sorry "+guests.pop(3))
#sorry d
print(guests)
print(guests+" welcome")
#c welcome
print(guests+" welcome")
#e welcome
#最后我想把列表清空
del guests
del guests
print(guests)


说明一下 #后面的是我预想的结果 但是一运行就出问题了
显示这个   跟我预想的完全不同
['a', 'b', 'c']
hello a welcome
['a', 'd', 'c']
b can not attend.
['a', 'd', 'c', 'e']
welcome a attend my this party!
welcome d attend my this party!
welcome c attend my this party!
welcome e attend my this party!
i find a big table,so we change the place
['f', 'a', 'g', 'd', 'c', 'e']
i am so sorry ,i only can invite two.
sorry a
sorry c
Traceback (most recent call last):
File "C:/Users/hp/Desktop/comp1002/自学/invitation.py", line 28, in <module>
    third = guests.pop(2)
IndexError: pop index out of range

suchocolate 发表于 2020-9-27 08:57:07

到这行【third = guests.pop(2)】的时候guests列表已经没有第2个元素了。

heidern0612 发表于 2020-9-27 09:06:04

因为你pop了两遍。first一遍pop,打印一遍pop。 正确的应该是

print ("sorry "+first)

并且这种pop完了之后,列表的下标完全都变了,5个元素变成4个元素,原来的1下标变成了0下标,导致你后面index超过列表长度了。

页: [1]
查看完整版本: 求大佬帮我瞅瞅我快哭了