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

标签 python python-3.x

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

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

关于将函数应用于链表的 Pythonic 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57957159/

相关文章:

python - bool = (boolean expression) 形式的语句是 Pythonic 的吗?

python - 使用 Python 和 MySQL 进行字符串编码

python - 以 ; 结尾的 Python 语句有什么区别?

python - 对 modelform_factory 表单中的字段进行重新排序

python - 根据python matplotlib中的数据集生成带有颜色渐变的网格

python - 在 Windows 上升级 pip.exe 时出现 "Access is denied"

Python 2.7 分割线无法通过尾随反斜杠分割

python - 将命令行参数从文件夹脚本传递到文件脚本

Python 一个列表中的两个列表,带 Tab

python - 如何让python脚本等待linux脚本完成