简体   繁体   中英

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:

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]

It throws this error:

name 'doc' is not defined

I understand the error but why does it say doc is undefined when I'm defining it in the list comprehension?

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.

For example, if there is an if condition in the list comprehension, you would write it as,

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

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

You see the if is now after for.
The same thing with double for loops too. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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