python列表修改,函数中的Python修改列表

I am trying to let a function modify a list by passing the list's reference to it. The program below shows when I pass a list into the function, only a local variable is generated. Is there any ways to select some members from that list within a function? Thank you.

def func(list1):

list1 = list1[2:]

print(list1) # prints [2, 3]

list1 = [0, 1, 2, 3]

func(list1)

print(list1) # prints [0, 1, 2, 3]

Edit1: I also tried to use the following function. It also doesn't work. Maybe it's because in func2 list1 becomes a local variable referencing to list2.

def func2(list1):

list2 = list1[2:]

list1 = list2

print(list1) # prints [2, 3]

list1 = [0, 1, 2, 3]

func(list1)

print(list1) # prints [0, 1, 2, 3]

解决方案

You have to return and assign the returned value to list1:

def func(list1):

list1 = list1[2:]

print(list1) # prints [2, 3]

return list1

list1=func(list1)

or you have to reference list1 as global inside func().

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值