[英]Element-wise add of two 3d lists through reduce
我有一個數組,其中包含a[0]
和a[1]
的2d數組和a[2]
一個1d數組。 我想通過reduce()
將map()
的結果與下一行進行聚合,但是由於數組a
的形式,我發現嘗試numpy會遇到一些困難。
例如:
a = [((1,6), (4,7), (4,5)), ((3,7), (8,2), (2,4)), (2,4,5)]
b = [((3,7), (8,2), (2,4)), ((6,5), (1,7), (4,8)), (7,2,1)]
result = [((4,13), (12,9), (6,9)), ((9,12), (9,9), (6,12)), (9,6,6)]
如何在python中做到這一點?
我必須想出這個難看的清單理解問題,但這至少可以起作用:
result = [tuple([tuple(row) if not isinstance(row, np.int64) else row for row in np.array(aa)+np.array(bb)]) for aa, bb in zip(a, b)]
a
Out[29]: [((1, 6), (4, 7), (4, 5)), ((3, 7), (8, 2), (2, 4)), (2, 4, 5)]
b
Out[30]: [((3, 7), (8, 2), (2, 4)), ((6, 5), (1, 7), (4, 8)), (7, 2, 1)]
result
Out[31]: [((4, 13), (12, 9), (6, 9)), ((9, 12), (9, 9), (6, 12)), (9, 6, 6)]
您可能需要對np.int64
進行調整,以將其設為默認的numpy int類型。
我認為使用map和lambda函數可以使它稍微好一些。
result = [tuple(map(lambda x: x if isinstance(x, np.int64) else tuple(x), np.array(aa)+np.array(bb))) for aa, bb in zip(a, b)]
此解決方案實現了zip
和map
一些簡單的遞歸嵌套版本:
def nested_map(fnc, it):
try:
return type(it)(nested_map(fnc, sub) for sub in it)
except TypeError:
return fnc(it)
def nested_zip(*iterables):
r = []
for x in zip(*iterables):
try:
r.append(type(x[0])(nested_zip(*x)))
except TypeError:
r.append(x)
return r
nested_map(sum, nested_zip(a, b))
# [((4, 13), (12, 9), (6, 9)), ((9, 12), (9, 9), (6, 12)), (9, 6, 6)]
此實現具有處理任意嵌套級別的額外靈活性:
nested_map(sum, nested_zip([(1, 2), 3, [4]], [(1, 2), 3, [4]]))
# [(2, 4), 6, [8]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.