Skip to main content
 首页 » 编程设计

将函数应用于链表的 Pythonic 方式

2025年05月04日17sxdcgaq8080

我想将函数应用于(链式)列表并尽可能以最优雅的方式保持结构。更准确地说,考虑

def fun(x, y): 
    return x+y 
 
list_1 = [[{'x': 3, 'y': 4}, {'x': 6, 'y': 5}], [{'x': 9, 'y': 4}, {'x': 1, 'y': 5}]] 
list_2 = [{'x': 6, 'y': 4}, {'x': 5, 'y': 5}] 

然后 list_1 的输出应该是 [[7, 11], [13, 6]] 而 list_2 [10, 10]。这可以通过使用

[[foo(**i) for i in this_sublist] for this_sublist in list_1] 
[foo(**i) for i in list_2] 

但是,我想避免区分不同的深度,而是有一个单一的声明。

请您参考如下方法:

递归方法:

def operate(v): 
    if isinstance(v, list): 
        return [operate(v) for v in v]  # or list(map(operate, v)) 
    elif isinstance(v, dict): 
        # use sum or whatever function you need on v 
        return sum(v.values()) 
    # implement whatever error handling logic you want in case v is neither  
    # a dict nor a list 
 
 
list_1 = [[{'x': 3, 'y': 4}, {'x': 6, 'y': 5}], [{'x': 9, 'y': 4}, {'x': 1, 'y': 5}]] 
list_2 = [{'x': 6, 'y': 4}, {'x': 5, 'y': 5}] 
list_3 = [[[{'x': 3, 'y': 4}, {'x': 6, 'y': 5}], [{'x': 9, 'y': 4}, {'x': 1, 'y': 5}]]] 
print([operate(v) for v in list_1]) 
print([operate(v) for v in list_2]) 
print([operate(v) for v in list_3]) 

输出

[[7, 11], [13, 6]] 
[10, 10] 
[[[7, 11], [13, 6]]]