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
l = ['a', 'b', 'c']
print(list(accumulate(l, '{}/{}'.format)))
This outputs:
['a', 'a/b', 'a/b/c']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With