nested list comprehension using intermediate result

Posted by KentH on Stack Overflow See other posts from Stack Overflow or by KentH
Published on 2012-06-26T15:01:14Z Indexed on 2012/06/26 15:16 UTC
Read the original article Hit count: 157

Filed under:

I am trying to grok the output of a function which doesn't have the courtesy of setting a result code. I can tell it failed by the "error:" string which is mixed into the stderr stream, often in the middle of a different conversion status message.

I have the following list comprehension which works, but scans for the "error:" string twice. Since it is only rescanning the actual error lines, it works fine, but it annoys me I can't figure out how to use a single scan. Here's the working code:

errors = [e[e.find('error:'):] for e in err.splitlines() if 'error:' in e]

The obvious (and wrong) way to simplify is to save the "find" result

errors = [e[i:] for i in e.find('error:') if i != -1 for e in err.splitlines()]

However, I get "UnboundLocalError: local variable 'e' referenced before assignment". Blindly reversing the 'for's in the comprehension also fails. How is this done?

THanks. Kent

© Stack Overflow or respective owner

Related posts about python