小编Ser*_*ina的帖子

是否可以在 python 的列表理解中调用函数(不是内置函数)?

假设我们有一个列表:

X = [1,2,3,4,5,6,7,8]
Run Code Online (Sandbox Code Playgroud)

我们创建了一个名为 add() 的函数:

def add():
  sum = 0
  result = 0
  for e in X:
    sum = sum + e
    return sum
add()
Run Code Online (Sandbox Code Playgroud)

它遍历数字 X 的列表,将列表中的下一个元素添加到前一个总和中。因此对于每个元素 X[i],我们有:

1
3
6
10
15
21
28
36
45
Run Code Online (Sandbox Code Playgroud)

现在,如果我想通过使用列表理解将这些结果再次放入列表中该怎么办?考虑到可以在列表推导式中应用内置函数,是否可以在列表推导式中调用诸如 add() 之类的函数?

我已经尝试过以下方法:

L = [add() for e in X]
print L
Run Code Online (Sandbox Code Playgroud)

这使

[None, None, None, None, None, None, None, None, None]
Run Code Online (Sandbox Code Playgroud)

代替

[1,3,6,10,15,21,28,36,45]
Run Code Online (Sandbox Code Playgroud)

为什么我在此列表中获得 NoneType 值?

python nested list-comprehension function

3
推荐指数
1
解决办法
719
查看次数

标签 统计

function ×1

list-comprehension ×1

nested ×1

python ×1