Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: complex list comprehensions 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 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?

like image 613
Albert Avatar asked Nov 09 '09 10:11

Albert


People also ask

How do list comprehensions work in Python?

List comprehensions provide us with a simple way to create a list based on some sequence or another list that we can loop over. In python terminology, anything that we can loop over is called iterable. At its most basic level, list comprehension is a syntactic construct for creating lists from existing lists.

How do you increment a variable in a list comprehension in Python?

To increment a variable in Python use the syntax += 1 , for example to increment the variable i by 1 write i += 1 .

Can list comprehensions be nested?

As it turns out, you can nest list comprehensions within another list comprehension to further reduce your code and make it easier to read still. As a matter of fact, there's no limit to the number of comprehensions you can nest within each other, which makes it possible to write very complex code in a single line.


1 Answers

It should work the other way around:

all = [x for t in tests for x in t[1]]
like image 81
Ferdinand Beyer Avatar answered Oct 23 '22 07:10

Ferdinand Beyer