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