简体   繁体   中英

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). Any changes are to be done only within the function 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:

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. My question is, is there anyway to modify L from within applyAdd(L, x) function.

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. 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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM