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

apply a function over each element of an iterable with sublists

我正在尝试将函数应用于包含任意子列表子级别的列表的每个元素。像这样。

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

这是一种方法。请注意,字符串也是可迭代的,因此根据您的用例,您可能需要添加更多检查。

def apply(iterable, f):
    try:
        iterator = iter(iterable)
        for i in iterator:
            apply(i, f)
    except Exception as e:
        f(iterable)

c = [[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]
apply(c, print)

听起来递归应该可以解决这个问题:

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]]]

试试这个递归:

def apply(it, func):
    try:
        return [apply(e) for e in it]
    except TypeError:
        return func(it)

请注意,除非您另有指定,否则这将遍历任何可迭代对象,例如,您可以在开头检查它是否是一个字典,然后将其应用到它上面的函数.. add

if isinstance(it,dict):
    func(it)

如果你所有的嵌套列表都是相同的形状,你应该可以用 numpy 做到这一点:

import numpy as np

ary = np.array([['a', 'b'], ['c', 'd'], ['e', 'f']])
res = np.vectorize(lambda c: c + ':)')(ary)
print(res)
# [['a:)' 'b:)']
#  ['c:)' 'd:)']
#  ['e:)' 'f:)']]