请大家帮忙看看,为什么运用了副本,原来的列表也空了

def transform_messages(messasges,sent_messages):

‘’’发送全部信息’’’

while messages:

sending_message=messages.pop()

print(f’sending message:{sending_message}’)

sent_messages.append(sending_message)

def send_messages(messages,sent_messages):

‘’’打印未发送信息和已发送信息两个列表’’’

print(‘Here are the original messages’)

for message in messages:

print(message)

print(‘Here are the sent messages’)

for sent_message in sent_messages:

print(sent_message)

messages=[‘A’,’B’,”C”,”D”,”E”,”F”]

sent_messages=[]

transform_messages(messages[:],sent_messages)

send_messages(messages,sent_messages)

sending message:F
sending message:E
sending message:D
sending message:C
sending message:B
sending message:A
Here are the original messages
Here are the sent messages
F
E
D
C
B
A

讨论数量: 1
Jason990420

List variable passed by address, not by value. You list variable will be changed at the same time when you change the content of it in anywhere.

Try using new varible for it, for example

    new_messages = messages.copy()
    while  new_messages:
        sending_message = new_messages.pop()
        print(f'sending message:{sending_message}')
        sent_messages.append(sending_message)
4天前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!