python - 列表理解输出

标签 python list list-comprehension

我试图通过传递一个函数列表来理解列表理解,如下面的代码所示。

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/

相关文章:

performance - haskell列表理解能力

java - JList 不显示我的组合框中新添加的元素

list - 如果原子在列表中则返回 True 的 LISP 函数

python - 为什么再次读取文件读取速度更快?

python - Flask : How are class member variables resetting when the class isn't being reinitialized? 的 Werkzeug 和类状态

java - 在 ArrayList 中查找重复值

python - 短路列表理解

haskell - 学习 haskell : Making a function that returns a list of elements that only appear once

python - 在 SQLAlchemy 中,列属性上的 group_by 在 1.0.0b1 中不再有效

python - 在 Python 中使用决策树进行文本分类