python - Apply function n-times, using output of last as input of next -
for example, when traversing multiple levels hierarchy using dirname
typically this.
grandparent = os.path.dirname(__file__) grandparent = os.path.dirname(grandparent)
or, in case of more levels.
grandparent = = os.path.dirname(__file__) x in xrange(5): grandparent = os.path.dirname(grandparent)
but wonder if there's less verbose method of doing this?
such as
grandparent = y(5, os.path.dirname, __file__)
where y
mysterious function i'm looking for.
and if not, such function called?
what defining such higher order function yourself:
def repeat (f, x, n) : in range(n): x = f(x) return x
with f
function wish call, x
first input in sequence, , n
number of times wish call this.
you can call instance with:
>>> repeat(lambda x: x**2,2,3) 256 >>> repeat(os.path.dirname,'/home/kommusoft/testfolder/sqldump', 2) '/home/kommusoft'
if plan walk root of directory, using large number of repetitions not safe: never know user has made cascade of over 9 thousand directories.
Comments
Post a Comment