guys. I\'m trying to find the most elegant solution to a problem and wondered if python has anything built-in for what I\'m trying to do.
What I\'m doing is this. I
You could try itertools.chain()
, like this:
import itertools
import os
dirs = ["c:\\usr", "c:\\temp"]
subs = list(itertools.chain(*[os.listdir(d) for d in dirs]))
print subs
itertools.chain()
returns an iterator, hence the passing to list()
.
def flat_list(arr):
send_back = []
for i in arr:
if type(i) == list:
send_back += flat_list(i)
else:
send_back.append(i)
return send_back
>>> from functools import reduce
>>> listOfLists = [[1, 2],[3, 4, 5], [6]]
>>> reduce(list.__add__, listOfLists)
[1, 2, 3, 4, 5, 6]
I'm guessing the itertools solution is more efficient than this, but this feel very pythonic.
In Python 2 it avoids having to import a library just for the sake of a single list operation (since reduce
is a built-in).
You could just do the straightforward:
subs = []
for d in dirs:
subs.extend(os.listdir(d))
You can use pyxtension:
from pyxtension.streams import stream
stream([ [1,2,3], [4,5], [], [6] ]).flatMap() == range(7)
import itertools
x=[['b11','b12'],['b21','b22'],['b31']]
y=list(itertools.chain(*x))
print y
itertools will work from python2.3 and greater