简体   繁体   English

为什么列表理解会给我项目未定义错误?

[英]Why does list comprehension give me item not defined error?

I have a pandas.Series of spacy.tokens.doc.Doc and I'm running this for loop:我有一个pandas.Seriesspacy.tokens.doc.Doc并且我正在运行这个 for 循环:

for doc in docs:
    print([(x.text, x.label_) for x in doc.ents])

But when I try to convert it into a list comprehension: [(x.text, x.label) for x in doc.ents for doc in docs]但是当我尝试将其转换为列表理解时: [(x.text, x.label) for x in doc.ents for doc in docs]

It throws this error:它抛出这个错误:

name 'doc' is not defined名称“doc”未定义

I understand the error but why does it say doc is undefined when I'm defining it in the list comprehension?我理解这个错误,但是当我在列表理解中定义它时,为什么它说 doc 未定义?

Your calling doc before it's defined.您的调用文档在定义之前。

[(x.text, x.label) for doc in docs for x in doc.ents]

This is a classic mistake with list comprehension that I make too.这也是我犯的列表理解的一个典型错误。
But you cannot be blamed for it.但你不能为此受到责备。 There might verywell be a logic to how the if/else/for is sequenced in these but my go to method is to try a simple example of it to get the sequence right. if/else/for 在这些中的排序方式很可能有一个逻辑,但我的 go 方法是尝试一个简单的示例来获得正确的序列。

For example, if there is an if condition in the list comprehension, you would write it as,例如,如果列表推导中有一个 if 条件,你可以写成,

Y = [x if (some_condition) for x in Xs]

So far so good.到目前为止,一切都很好。 But if there is an else statement in it, this would become something like但是如果里面有一个 else 语句,这将变成类似

Y = [x1 for x1,x2 in Xs if (some_condition) else x2]

You see the if is now after for.你看 if 是现在之后的 for。
The same thing with double for loops too.双 for 循环也是如此。 You can simply try你可以简单地尝试

foo = [c for c in bar for bar in ["foo", "bar"]]

and

foo = [c for bar in ["foo", "bar"] for c in bar]

and go with whatever works.和 go 与任何工作。 That's easier than remembering it.这比记住它容易。 Or just remember that for double for, if one sequence didn't work, it's the other way round或者只是记住,对于 double for,如果一个序列不起作用,则相反

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

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