简体   繁体   English

在附加到列表时应用 lambda function

[英]Apply a lambda function while appending to a list

Imagine a one dimensional array 'inter' and an empty list 'visual_pred'.想象一个一维数组“inter”和一个空列表“visual_pred”。 I want to iterate over all elements in the array and append each element to my list while adding the element with the list's last entry.我想遍历数组中的所有元素和 append 每个元素到我的列表中,同时添加带有列表最后一个条目的元素。

My code looks like this:我的代码如下所示:

visual = []

for x in inter:
    if x > 0:
        visual.append(lambda x: x + visual[-1])
    else:
        visual.append(visual[-1])

After executing the code all entries in my list 'inter' looks like this: 执行代码后,我的列表“inter”中的所有条目如下所示:
 function __main__.lambda(x)

What is the problem here and how can I challenge it?这里有什么问题,我该如何挑战它?

What you're doing here is appending the lambda function itself to your list and not the lambda functions output.您在这里所做的是将 lambda function 本身而不是 lambdaF3D148E62281F3989 函数附加到您的列表中I don't actually see why you need a lambda here anyway.无论如何,我实际上不明白为什么您需要 lambda 。 This does what you want.这可以满足您的需求。

visual = []

for x in inter:
    if x > 0:
        visual.append(x + visual[-1])
    else:
        visual.append(visual[-1])

As BeanBagTheCat pointed out, you're appending the lambda function itself to your list and not the lambda functions output. As BeanBagTheCat pointed out, you're appending the lambda function itself to your list and not the lambda functions output. You can write the same code by BeanBagTheCat in one line using list-comprehension as follows:您可以使用列表理解在一行中通过BeanBagTheCat编写相同的代码,如下所示:

visual = [x + visual[-1] if x > 0 else visual[-1] for x in inter]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM