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

  • A+

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'] 


You can use itertools.accumulate():

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

This outputs:

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


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: