guys. I am trying to find the most elegant solution to the problem and wondering if python has something built in for what I'm trying to do.
What I do is this. I have a list A , and I have a function f that takes an element and returns a list. I can use list comprehension to convert everything to A like this:
[f(a) for a in A]
But this returns a list of lists,
[a1,a2,a3] => [[b11,b12],[b21,b22],[b31,b32]]
I really want a flattened list,
[b11,b12,b21,b22,b31,b32]
Now, in other languages; it is traditionally called flatmap in functional programming languages, and .Net calls it SelectMany . Does python have something like this? Is there a neat way to map a function over a list and smooth out the result?
The actual problem I'm trying to solve is the following; starting with the directory listing, find all the subdirectories. So;
import os dirs = ["c:\\usr", "c:\\temp"] subs = [os.listdir(d) for d in dirs] print subs
currentliy gives me a list of lists, but I really need a list.
python functional-programming list-comprehension
Steve Cooper Jul 02 '09 at 10:40 2009-07-02 22:40
source share