Python: complex lists of lists, where one var depends on another (x for x in t [1] for t in tests)

I want to do something like:

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

tests are as follows:

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

So I want to get the result

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

My code is not working, Python says:

 UnboundLocalError: local variable 't' referenced before assignment 

Is there an easy way to do this?

+7
python list-comprehension
source share
4 answers

It should work the other way around:

 all = [x for t in tests for x in t[1]] 
+15
source share

If in doubt, do not use lists.

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

 Explicit is better than implicit 

This type of list compilation can cause many Python programmers to at least add a comment to explain that you are deleting lines and aligning the rest of the list.

Use lists where they are understandable and understandable, and especially use them when they are idiomatic, that is, they are widely used because they are the most effective or elegant way to express something. For example, 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 understandable. Attachment list attachments are not so bad if you pay attention to formatting and maybe add a comment because the brackets help the reader to decompose the expression. But the decision made for this problem is too complicated and confusing, in my opinion. It goes beyond the boundaries and makes the code unreadable for too many people. It’s better to deploy at least one iteration in a for loop.

+5
source share

If all you are doing is combining multiple lists, try the built-in sum, using [] as the starting value:

 all = sum((t[1] for t in tests), []) 
+2
source share

It looks like a cut. Unfortunately, Python does not offer any syntactic sugar to reduce, so we should use lambda:

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

All Articles