如何防止列表在用作函数中的参数后发生更改? [英] How to prevent a list from changing after being used as parameter in function?

查看:34
本文介绍了如何防止列表在用作函数中的参数后发生更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码没有按照我想要的方式输出结果.

I have a little code which is not outputting the result as I wanted.

代码

def func_a(list1):
    list1.insert(2,'3')
    list1.append('c')
    return (list1)

def main():
    list_1 = ['1','2','a','b']    
    list_2 = func_a(list_1)
    print (list_1)
    print ("\n")
    print (list_2)

main()

此代码的输出为:

['1', '2', '3', 'a', 'b', 'c']


['1', '2', '3', 'a', 'b', 'c']

我希望它是:

['1', '2', 'a', 'b']


['1', '2', '3', 'a', 'b', 'c']

推荐答案

您必须创建列表的副本,并对其进行修改:

You have to create a copy of the list, and modify that:

def func_a(list1):
    list1copy = list1[:]
    list1copy.insert(2,'3')
    list1copy.append('c')
    return (list1copy)

您也可以保持 func_a 不变,只需使用列表的副本调用即可:

You could also keep func_a the same, and just call it with a copy of the list:

list_2 = func_a(list_1[:])

这篇关于如何防止列表在用作函数中的参数后发生更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆