为什么我的变量在使用pop()方法时不更新?

2024-04-25 13:58:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在通过Python速成班学习Python,我在列表一章。你知道吗

我有一个客人列表,我应该为每个人打印一条消息(还没有循环),在其中我必须使用pop()方法告诉他们没有被邀请参加活动。你知道吗

#I tried this :

removed_guest = guestlist.pop()
apology = 'you cannot come to dinner ' + removed_guest
print(apology)
print(apology)
print(apology)


#but I figured the variable needs to be updated for each print

#I tried re-adding the removed_guest variable for each print:


removed_guest = guestlist.pop()
apology = 'you cannot come to dinner ' + removed_guest
print(apology)
removed_guest = guestlist.pop()
print(apology)
removed_guest = guestlist.pop()
print(apology)


#but this is where I made a mistake because the same thing happens (shouldn't removed guest list update with the newest last item in the list since I already popped that one out?

#at last I did this:

apology = 'you cannot come to dinner '
print(apology + guestlist.pop())
print(apology + guestlist.pop())
print(apology + guestlist.pop())

#this works but I'm curious as to why the apology variable doesn't get updated even though I updated remove_guest.

Tags: thetoyouthisvariablepopbutprint
3条回答

如果我清楚地理解您的查询,那么您只在每个print命令之前更新已删除的\u guest变量(而不是道歉变量),但希望道歉也得到更新。你知道吗

为了更新道歉,您需要在每个打印命令之前更新道歉:

removed_guest = guestlist.pop()
apology = 'you cannot come to dinner ' + removed_guest
print(apology)
removed_guest = guestlist.pop()
apology = 'you cannot come to dinner ' + removed_guest
print(apology)
removed_guest = guestlist.pop()
apology = 'you cannot come to dinner ' + removed_guest
print(apology)

赋值语句(x=y)在执行时为x赋值;它们不定义导致该操作重复的某种关系。你知道吗

this works but im curios as to why the apology variable doesnt get updated even tho i updated remove_guest

我相信你是说这里?你知道吗

removed_guest = guestlist.pop()
apology = 'you cannot come to dinner ' + removed_guest
print(apology)
removed_guest = guestlist.pop()
print(apology)
removed_guest = guestlist.pop()
print(apology)

假设我们有客人A,B和C。 所以你的代码是这样的。在第一行,被删除的客人将被设置为C。然后你会说道歉是“你不能来就餐”+“C”。你会把这个打印出来。然后你会说删除的客人被设置为B。然后你会打印道歉。然后你会说被除名的客人是一个,然后你会打印道歉。但是正如你所看到的,道歉只设定了一次,客人是C。但是道歉的内容总是“你不能来就餐”+“C”。你知道吗

相关问题 更多 >