Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ('a', 'a/b', 'a/b/c') from ('a', 'b', 'c')?

Tags:

python

How can I go from this structure

>>> input = ['a', 'b', 'c']

to this one

>>> output 
['a', 'a/b', 'a/b/c']

in an elegant (functional) way?

For now I have this:

>>> from functools import reduce
>>> res = []
>>> for i in range(len(input)):
...     res.append(reduce(lambda a, b: a + '/' + b, input[:i+1]))
... 
>>> res
['a', 'a/b', 'a/b/c']
like image 910
user3313834 Avatar asked Dec 02 '22 09:12

user3313834


1 Answers

You can use itertools.accumulate():

from itertools import accumulate
l = ['a', 'b', 'c']
print(list(accumulate(l, '{}/{}'.format)))

This outputs:

['a', 'a/b', 'a/b/c']
like image 100
blhsing Avatar answered Dec 04 '22 00:12

blhsing