如何制作对两个或多个相同形状的嵌套列表进行操作的Python函数?

时间:2019-03-28 20:54:32

标签: python list

我想对两个或多个相同形状的嵌套列表应用任意函数。例如,如果我的功能是:

def add(a, b):
    if "NULL" not in [a, b]:
        return a + b
    else:
        return "NULL"

我的输入是:

input1 = [[1, 2, "NULL"], [3, 4], [5, 6, 7, 8]]
input2 = [[9, 8, "NULL"], [7, 6], [5, 4, 3, 2]]

然后我希望输出为

output = [[10, 10, "NULL"], [10, 10], [10, 10, 10, 10]]

输入总是嵌套一层,但是理想情况下输出应该是任何东西(例如,如果该函数是“ concatenate(a,b)”函数,则可以嵌套得更深)

2 个答案:

答案 0 :(得分:2)

怎么样:

def apply_f(a, b, f):
    if isinstance(a, list):
        return [apply_f(item_a, item_b, f) for item_a, item_b in zip(a, b)]
    else:
        return f(a, b)

result = apply_f(input1, input2, add)

答案 1 :(得分:0)

假设列表总是正确的长度(您可以对此进行检查),使函数递归:

$result = $stmt->execute();
if ($result) {
    error_log("row inserted successfully");
} 
else {
    error_log("insert FAILED");
}

输出:

def add(a, b):

    if isinstance(a, list) and isinstance(b, list):
        for a_sub, b_sub in zip(a, b):
            return [add(a_sub, b_sub) for a_sub, b_sub in zip(a, b)]

    elif "NULL" not in [a, b]:
        return a + b

    elif "NULL" in [a, b]:
        return "NULL"

    else:
        raise ValueError("Wrong input shapes")

input1 = [[1, 2, "NULL"], [3, 4], [5, 6, 7, 8]]
input2 = [[9, 8, "NULL"], [7, 6], [5, 4, 3, 2]]

add(input1, input2)