您的位置:首页 > 编程语言 > Python开发

Python函数第三节

2016-07-23 14:43 579 查看
# 3.定义一个方法list_info(list), 参数list为列表对象,怎么保证在函数里对列表list进行一些相关的操作,
# 不会影响到原来列表的元素值,比如:a = [1,2,3]

a = [1, 2, 3]

def list_info(list_m):
temp = [list_m[i] for i in range(0, len(list_m))]
temp[0] = 5
return temp
print a
print list_info(a)
print a
[1, 2, 3]
[5, 2, 3]
[1, 2, 3]


在这里面需要注意的是,函数里面直接写temp=list_m的话在改变temp的过程中,会改变list_m的值
a = [1, 2, 3]

def list_info(list_m):
temp = list_m
temp[0] = 5
return temp
print a
print list_info(a)
print a
[1, 2, 3]
[5, 2, 3]
[5, 2, 3]
可以看下不加函数就直接对列表进行操作的情况:
a = [1, 2, 3]
temp = a
temp[0] = 5
print temp
print a
[5, 2, 3]
[5, 2, 3]
再看一下对于单个数值的情况:
a = 1
temp = a
temp = 5
print temp
print a
5
1


再来改变源对象的值,看看所赋值对象的变化:
a = 1
temp = a
a = 5
print temp
print a
1
5
对于列表的情况:
a = [1, 2, 3]
temp = a
a[0] = 5
print temp
print a

[5, 2, 3]
[5, 2, 3]


对于函数的情况下:
a = [1, 2, 3]

def list_info(list_m):
temp = list_m
list_m[0] = 5
return temp
print a
print list_info(a)
print a

[1, 2, 3]
[5, 2, 3]
[5, 2, 3]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: