简体   繁体   English

在列表推导式中对 lambdas 进行热切评估

[英]Eager evaluation of lambdas within a list comprehension

Consider a python function:考虑一个python函数:

def testSetsFromStrings(tt):
  x1= [lambda x: x.split(' ') for t in tt]
  return x1

Let's invoke it with the following :让我们用以下命令调用它:

tt = ['id0 id1 id2 id3 id4', 
'id10 id11 id12 id13 id14', 
'id20 id21 id22 id23 id24', 
' id30 id31 id32 id33 id34', 
'id50 id51 id52 id53 id54']

testSetFromStrings(tt)

A breakpoint was placed after the x1= .. line and we can see x1 =x1= ..行之后放置了一个断点,我们可以看到x1 =

<class 'list'>: [<function testSetsFromStrings.<locals>.<listcomp>.
<lambda> at 0x11cee5730>, <function testSetsFromStrings.<locals>.<listcomp>.
<lambda> at 0x11cee5840>, <function testSetsFromStrings.<locals>.<listcomp>.
<lambda> at 0x11cee58c8>, <function testSetsFromStrings.<locals>.<listcomp>.
<lambda> at 0x11cee5950>, <function testSetsFromStrings.<locals>.<listcomp>.
<lambda> at 0x11cee59d8>]

I am at a loss as to how to cause that lambda to be eagerly evaluated.我不知道如何使该lambda急切地评估。 What can be done here?在这里可以做什么?

** Update** ** 更新**

The logic shown is a simplification of the multi step function that is needed: to focus on just the mechanics of invoking a lambda.显示的逻辑是所需的多步函数的简化:只关注调用 lambda 的机制。 Replacing the lambda with directly invoking split does not address the real need.用直接调用split替换lambda并不能满足真正的需求。

Perhaps you don't want lambdas at all?也许你根本不想要 lambdas? Is this what you want?这是你想要的吗?

def testSetsFromStrings(tt):
    x1 = [x.split(' ') for x in tt]
    return x1

Lambdas are functions: they are evaluated when you call them. Lambda 是函数:当您调用它们时,它们会被评估。 If you want them to run immediately, then you probably don't need a lambda at all.如果您希望它们立即运行,那么您可能根本不需要 lambda。

If you need to invoke a function, then invoke it:如果你需要调用一个函数,那么调用它:

def testSetsFromStrings(tt):
    x1 = [my_function(x) for x in tt]
    return x1

You're defining the function, but not applying any arguments to it:您正在定义函数,但未对​​其应用任何参数:

Try this instead试试这个

x1 = [(lambda x: x.split(' '))(x) for x in tt]

But it would be better to just extract the function definition outside of the comprehension if the function is at all complicated and then use a map or list comprehension.但是,如果函数完全复杂,那么最好只提取推导式之外的函数定义,然后使用映射或列表推导式。

You could also use a map function instead of a list comprehension:您还可以使用 map 函数而不是列表理解:

x1 = map(lambda x: x.split(' '), tt)

if you prefer the lamda function being present.如果您更喜欢存在 lamda 函数。 Elsewhere just:在其他地方只是:

x1 = [x.split(' ') for x in tt]

as mentioned from others as well.正如其他人提到的那样。

What you need to understand is that lambdas are inherently functions themselves.您需要了解的是,lambda 本身就是函数。 Therefore, create a lambda function and invoke that.因此,创建一个 lambda 函数并调用它。

testSetsFromStrings = lambda x: x.split(' ')
x1 = [testSetsFromStrings(t) for t in tt]

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

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