-, , [[1,2], [[5]], [7, [8, [9,11]]]]:
def apply_f(a,f):
if isinstance(a,list):
return map(lambda t:apply_f(t,f), a)
else:
return f(a)
:
>>> ll=[[1,2],[[5]],[7,[8,[9,11]]]]
>>> apply_f(ll,lambda t:t**2)
[[1, 4], [[25]], [49, [64, [81, 121]]]]
:
def apply_f(a,f,depth,levels):
if isinstance(a,list):
return map(lambda t:apply_f(t,f,depth+1,levels), a)
else:
if depth in levels:
return f(a)
else:
return a
>>> apply_f(ll,lambda t:t**2, 0, [2,4])
[[1, 4], [[5]], [49, [8, [81, 121]]]]
, f levels ( , f levels ), . ( , Python 2, Python 3 map - ).
, :
def apply_f(a,f):
try:
return(f(a))
except:
return map(lambda t:apply_f(t,f), a)
:
>> apply_f([(1,2),[[5]],[7,(8,[9,11])]],lambda t:t**2)
[[1, 4], [[25]], [49, [64, [81, 121]]]]
( , map() ...)