MAY*_*MAY 2 python python-2.7 python-3.x
我有一些代码没有按照我的意愿输出结果。
代码
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()
Run Code Online (Sandbox Code Playgroud)
此代码的输出是:
['1', '2', '3', 'a', 'b', 'c']
['1', '2', '3', 'a', 'b', 'c']
Run Code Online (Sandbox Code Playgroud)
我希望它是:
['1', '2', 'a', 'b']
['1', '2', '3', 'a', 'b', 'c']
Run Code Online (Sandbox Code Playgroud)
您必须创建列表的副本,并对其进行修改:
def func_a(list1):
list1copy = list1[:]
list1copy.insert(2,'3')
list1copy.append('c')
return (list1copy)
Run Code Online (Sandbox Code Playgroud)
您也可以保持func_a不变,只需使用列表的副本调用它:
list_2 = func_a(list_1[:])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
812 次 |
| 最近记录: |