将操作和列表应用于嵌套列表

Azs*_*sgy -1 python iterator functional-programming list multidimensional-array

迭代嵌套列表有很多问题,但是我想迭代嵌套列表并应用另一个列表.

这是我的场景:

def operation(a, b):
    return a + b

def magic_function(func, list, nested_list):
    """iterate over nested_list and apply the next element of list"""
    ...

magic_function(operation, [0, 0, 0, 10, 10, 10], [[1, 2, 3], [1, 2, 3]])
Run Code Online (Sandbox Code Playgroud)

期望的输出:

[[1, 2, 3], [11, 12, 13]]
Run Code Online (Sandbox Code Playgroud)

用numpy回答这个问题的冲动可能很强烈,但在实际情况中,这些是对象,而不是数字.

该标准itertools.chain.from_iterable在此处不起作用,因为它不保留列表的嵌套.

Kev*_*vin 5

这是一个适用于任意深度嵌套列表的实现:

def nested_map(f, obj):
    if isinstance(obj, list):
        return [nested_map(f, item) for item in obj]
    else:
        return f(obj)

def magic_function(func, seq, nested_list):
    g = iter(seq)
    return nested_map(lambda item: func(item, next(g)), nested_list)

def operation(a, b):
    return a + b

result = magic_function(operation, [0, 0, 0, 10, 10, 10], [[1, 2, 3], [1, 2, [[3]]]])
print(result)
Run Code Online (Sandbox Code Playgroud)

结果:

[[1, 2, 3], [11, 12, [[13]]]]
Run Code Online (Sandbox Code Playgroud)