[英]modify variables outside of function scope from within a function in python 3.5
How can I obtain the following result? 如何获得以下结果? I want to mutate
L
(list of integers) to contain only values, if value is greater than x
(any integer). 我想将
L
(整数列表)突变为仅包含值(如果value大于x
(任何整数))。 Any changes are to be done only within the function applyAdd(L, x)
. 任何更改都只能在函数
applyAdd(L, x)
。
def applyAdd(L, x):
L =[i for i in L if i>x]
return max(L)
when the following input is give in IPython console: 在IPython控制台中提供以下输入时:
L = [0, -10, 5, 6, -4]
print(applyAdd(L, 3))
print(L)
I get the following output 我得到以下输出
6
[0, -10, 5, 6, -4]
Instead I want 相反,我想要
6
[5, 6]
I know L
doesn't have scope outside of the function. 我知道
L
在函数之外没有作用域。 My question is, is there anyway to modify L
from within applyAdd(L, x)
function. 我的问题是,是否有从
applyAdd(L, x)
函数内部修改L
问题。
I got this as assignment, any help is much appreciated, thanks. 我把这作为任务,非常感谢您的帮助。
This is not working, because the generator will new a new list inside function. 这是行不通的,因为生成器将在函数内部新建一个新列表。
def applyAdd(L, x):
L =[i for i in L if i>x]
print(id(L)) #some different value
L = [0, -10, 5, 6, -4]
print(id(L)) #some value
Solution1. 解决方法1。 Use global variable instead
改用全局变量
L = [0, -10, 5, 6, -4]
def applyAdd(x):
global L
L =[i for i in L if i>x]
return max(L)
print(applyAdd(3))
print(L)
Solution2. 解决方案2。 Keep using generator
继续使用发电机
def applyAdd(L, x):
X = ([i for i in L if i>x])
L.clear()
L.extend(X)
return max(L)
L = [0, -10, 5, 6, -4]
print(applyAdd(L, 3))
print(L)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.