Python 修改函数内的全局变量

Python revise global variables inside function

背景

假设我有2个全局变量a = [1,2,3]b = ['a','b'],如果我必须在一个函数中交换ab,我可以用下面的代码:

a = [1,2,3]
b = ['a','b']
def fun1():
    global a,b
    temp = a[::-1]
    a = b[::-1]
    b = temp
fun1()
print(a,b)

输出:

['b', 'a'] [3, 2, 1]

但是,如果 ab 是我函数的参数,我们该怎么做呢?

a = [1,2,3]
b = ['a','b']
def fun2(a,b):
    global a,b
    temp = a[::-1]
    a = b[::-1]
    b = temp
fun2(a,b)
print(a,b)

引发错误:

SyntaxError: name 'a' is parameter and global

我的尝试

我尝试使用 exec,它适用于 Python 3.7,但是,它不适用于 Codewars 3.6 env。 我不知道不知道是什么原因,可能是方法找错了

a = [1,2,3]
b = ['a','b']
def exchange_with(a, b):
    temp = a[::-1].copy()
    exec('a = b[::-1]',globals())
    exec('b = temp',locals(),globals())
exchange_with(a, b)
a,b

输出:

(['b', 'a'], [3, 2, 1])

您仍然必须将值作为参数传递。进入函数后,您需要对每个列表进行就地切片分配。不需要涉及全局名称。

def fun2(a,b):
    a[:], b[:] = b[::-1], a[::-1]

x = [1,2,3]
y = ['a', 'b']
fun2(x, y)
assert x == ['b', 'a']
assert y == [3, 2, 1]