假设我们有一个列表:
X = [1,2,3,4,5,6,7,8]
我们创建了一个名为 add() 的函数:
def add():
sum = 0
result = 0
for e in X:
sum = sum + e
return sum
add()
遍历数字列表 X,将列表中的下一个元素添加到前一个总和中。所以对于每个元素 X[i],我们有:
1
3
6
10
15
21
28
36
45
现在,如果我想通过使用列表理解将这些结果再次放入列表中怎么办。是否可以在列表理解中调用诸如 add() 之类的函数, 考虑到可以在列表理解中应用内置函数?
我尝试了以下方法:
L = [add() for e in X]
print L
给出
[None, None, None, None, None, None, None, None, None]
代替
[1,3,6,10,15,21,28,36,45]
为什么我在此列表中得到 NoneType 值?
最佳答案
您可以使用 yield
执行此操作以保持原始格式:
X = [1,2,3,4,5,6,7,8]
def add():
sum = 0
for e in X:
sum = sum + e
yield sum
L = [value for value in add()]
print L
关于python - 是否可以在 python 的列表理解中调用函数(不是内置函数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25465264/