我试图通过传递一个函数列表来理解列表理解,如下面的代码所示。
def fun1(x):
x.append(5)
print(" In Fun 1:")
print(x)
return x
def fun2(x):
x.append(6)
return x
def fun3(x):
x.append(7)
return x
int_list = [1, 2, 3, 4]
funs_family = (fun1, fun2, fun3)
new_list = [fun(int_list) for fun in funs_family ]
print(new_list)
我期望 new_list 的结果是
[1,2,3,4,5] [1,2,3,4,5,6] [1,2,3,4,5,6,7]
但实际结果是
[1,2,3,4,5,6,7] [1,2,3,4,5,6,7] [1,2,3,4,5,6,7]
谁能解释一下为什么实际结果与预期结果不同?
最佳答案
在您的 fun_family
方法中返回一个新列表,您将不会看到该问题:
def fun1(x):
x.append(5)
print("In Fun 1:")
print(x)
return list(x)
def fun2(x):
x.append(6)
return list(x)
def fun3(x):
x.append(7)
return list(x)
int_list = [1, 2, 3, 4]
funs_family = (fun1, fun2, fun3)
new_list = [fun(int_list) for fun in funs_family]
print(new_list)
>> [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6, 7]]
关于python - 列表理解输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56564723/