对带有子列表的可迭代对象的每个元素应用函数

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,但这当然不是解决方案,因为列表的内容也可以是字符串、对象......

Pat*_*ner 6

听起来递归应该能够解决这个问题:

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)

  • 这。除非我测试 isinstance(iterable, collections.abc.Iterable) (2认同)
  • @adir,虽然你的陈述是正确的 - 问题中使用的示例可迭代是一个列表。为此,它工作得很好 - 它不适用于字符串、字典或元组等。但对于那些 @Jérôme 建议使用“isinstance(iterable, collections.abc.Iterable)”的人来说,会起作用。 (2认同)