Multilevel list comprehensions in PythonPython has recently (at least for some values of recently) grown
'list comprehensions',
which let you easily iterate over a list to transform or select
entries (or both). List comprehensions can be thought of as syntactic
sugar for One reason is that you can write a multilevel list comprehension, which effectively iterates over multiple levels of lists. Take the case where you have a list within a list and want to return all of the low-level elements as a list:
This can be rewritten as a two-level list comprehension: l = [s for rr in qa for s in rr.strings] This can't easily be done via Multilevel list comprehensions work left to right; the leftmost 'for X in Y' is the outermost one, and then we step inwards as we move right. You can also use if conditions, so the correct version of the list comprehension I wrote, in context and with error checking, would be:
What impresses me about Python is that this works just the way I thought it would work and both of these examples worked the first time, just as I wrote them, and needed no debugging. (The first version actually got used in a scratch program.) |
These are my WanderingThoughts GettingAround This is part of CSpace, and is written by ChrisSiebenmann. * * * Atom feeds are available; see the bottom of most pages. Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web |