gpt4 book ai didi

Python 逐元素就地添加

转载 作者:太空宇宙 更新时间:2023-11-04 09:13:31 26 4
gpt4 key购买 nike

场景如下:给定 n 个整数列表(长度相同)和一个累加器(实际上长度相同),就地累加按元素求和。就地约束在这里是因为我在列表的字典中积累了值(嗯...不太清楚,请参见下面的示例)

编辑:我正在寻找不涉及 numpy 的解决方案

# My lists are long (they are actually pixels in 1000x1000 images)
# but I keep l low for the sake of the example
l = 5

# Values here are arbitrary and won't be repeated in the real word
# e.g. list 1 might be [41,15,0,2,3], etc.
lists = [
{'id': 1, 'values': [12]*l},
{'id': 2, 'values': [42]*l},
{'id': 2, 'values': [25]*l},
{'id': 1, 'values': [6]*l},
]

maps = {
1: [0]*l,
2: [0]*l
}

for item in lists:
# Get the "target" for this list
target = maps[item['id']]

# Element-wise addition of item['values'] to target here!

# This won't work
target = map(lambda x,y:x+y, target, item['values'])
# This neither
target = [(x+y) for x,y in itertools.izip(target,item['values'])]

# For either of the previous to work, I need to re-assign
# the result to 'target', like so
maps[item['id']] = target

虽然它有效并且我可以专业地接受它,但我个人不能。

谁能让我今晚睡得更好?

最佳答案

看看numpy .您的代码可以写成:

import numpy as np

l = 5
lists = [
{'id': 1, 'values': np.array([12]*l)},
{'id': 2, 'values': np.array([42]*l)},
{'id': 2, 'values': np.array([25]*l)},
{'id': 1, 'values': np.array([6]*l)},
]

maps = {
1: np.zeros(l),
2: np.zeros(l)
}

for item in lists:
maps[item['id']] += item['values']

您也可以将其调整为 2D(图像),无需进一步循环。

关于Python 逐元素就地添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12215766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com