对带有子列表的可迭代对象的每个元素应用函数
我试图将一个函数应用于包含任意子列表子级别的列表的每个元素。像这样。
a = [1,2,3]
b = [[1,2,3],[4,5,6]]
c = [[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]
function = lambda x: x+1
def apply(iterable,f):
# do stuff here
print(apply(a,function)) # [2,3,4]
print(apply(b,function)) # [[2,3,4],[5,6,7]]
print(apply(c,function)) # [[[2,3,4],[5,6,7]],[[8,9,10],[11,12,13]]]
基本上我找不到编写apply函数的方法。我尝试过 numpy,但这当然不是解决方案,因为列表的内容也可以是字符串、对象......
回答
听起来递归应该能够解决这个问题:
a = [1,2,3]
b = [[1,2,3], [4,5,6]]
c = [[[1,2,3], [4,5,6]], [[7,8,9], [10,11,12]]]
f = lambda x : x+1
def apply(iterable, f):
# suggestion by Jérôme:
# from collections.abc import Iterable and use
# isinstance(iterable, collections.abc.Iterable) so it works for tuples etc.
if isinstance(iterable, list):
# apply function to each element
return [apply(w, f) for w in iterable]
else:
return f(iterable)
print(apply(a, f)) # [2,3,4]
print(apply(b, f)) # [[2,3,4],[5,6,7]]
print(apply(c, f)) # [[[2,3,4],[5,6,7]],[[8,9,10],[11,12,13]]]
- This. Except I'd test isinstance(iterable, collections.abc.Iterable)
- @adir while your statement is correct - the example iterable used in the question is a list. For that it works fine - it would not work for a string or dict or tuple etc. but for those @ Jérôme suggestion to use `isinstance(iterable, collections.abc.Iterable)` would work.