开发者

Python: complex list comprehensions where one var depends on another (x for x in t[1] for t in tests)

I wa开发者_StackOverflow社区nt to do something like:

all = [ x for x in t[1] for t in tests ]

tests looks like:

[ ("foo",[a,b,c]), ("bar",[d,e,f]) ]

So I want to have the result

all = [a,b,c,d,e,f]

My code does not work, Python says:

UnboundLocalError: local variable 't' referenced before assignment

Is there any simple way to do that?


It should work the other way around:

all = [x for t in tests for x in t[1]]


When in doubt, don't use list comprehensions.

Try import this in your Python shell and read the second line:

Explicit is better than implicit

This type of compounding of list comprehensions will puzzle a lot of Python programmers so at least add a comment to explain that you are removing strings and flattening the remaining list.

Do use list comprehensions where they are clear and easy to understand, and especially, do use them when they are idiomatic, i.e. commonly used because they are the most efficient or elegant way to express something. For instance, this Python Idioms article gives the following example:

result = [3*d.Count for d in data if d.Count > 4]

It is clear, simple and straightforward. Nesting list comprehensions is not too bad if you pay attention to formatting, and perhaps add a comment because the braces help the reader to decompose the expression. But the solution that was accepted for this problem is too complex and confusing in my opinion. It oversteps the bounds and makes the code unreadable for too many people. It is better to unroll at least one iteration into a for loop.


If all you are doing is adding together some lists, try the sum builtin, using [] as a starting value:

all = sum((t[1] for t in tests), [])


That looks like a reduce to me. Unfortunately Python does not offer any syntactic sugar for reduce, so we have to use lambda:

reduce(lambda x, y: x+y[1], tests, [])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜