将函数应用于链表的Python方式
我想将一个函数应用于(链接的)列表,并尽可能以最优雅的方式保持结构。更准确地说,考虑将函数应用于链表的Python方式,python,python-3.x,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}] 然后列表_1的输出应该是[[7,11],[13,6],而列表_2的输出应该是[10,1
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}]
然后列表_1
的输出应该是[[7,11],[13,6]
,而列表_2的输出应该是[10,10]
。这可以通过使用
[[foo(**i) for i in this_sublist] for this_sublist in list_1]
[foo(**i) for i in list_2]
但是,我希望避免区分不同的深度,而是使用单个语句。您可以使用isinstance
检查obj
ect的类型是否为列表:
def bar(l):
return [[fun(**i) for i in obj] if isinstance(obj, list) else fun(**obj) for obj in l]
print(bar(list_1))
print(bar(list_2))
输出:
[[7, 11], [13, 6]]
[10, 10]
您可以使用isinstance
检查obj
ect的类型是否为列表:
def bar(l):
return [[fun(**i) for i in obj] if isinstance(obj, list) else fun(**obj) for obj in l]
print(bar(list_1))
print(bar(list_2))
输出:
[[7, 11], [13, 6]]
[10, 10]
递归方法:
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]]]
递归方法:
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]]]
你所追求的可以通过递归实现,虽然你不必区分不同的情况,但它不仅仅是一条语句。你所追求的可以通过递归实现,尽管你不必区分不同的情况,这将不仅仅是一条语句..如果它的3lvls deep?@Ev.Kounis按照OP的例子,只有两个深度级别,但肯定DeepSpace的递归方法更适合具有可变深度的结构。如果它的3lvls deep?@Ev.Kounis按照OP的例子,只有两个深度级别,但对于深度可变的结构来说,DeepSpace的递归方法肯定更好。