Giu*_*pox 3 python iterable list python-3.x
我试图将一个函数应用于包含任意子列表子级别的列表的每个元素。像这样。
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
Run Code Online (Sandbox Code Playgroud)
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]]]
Run Code Online (Sandbox Code Playgroud)
基本上我找不到编写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]]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
165 次 |
| 最近记录: |