Python 逐元素就地添加

标签 python

场景如下:给定 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/

相关文章:

python - 如何使用 rpy2 将日期从 Python 传递到 R

python - undefined symbol : PyArray_API when using numpy and swig

python - 将str列表转换为int python列表

python - 从枚举类获取值,其中枚举成员名称在 Python 中运行时已知

python - Python 的 super() 内置不是违反了 DRY 吗?

python - 如何在 python 中将 excel 自动化为 xml?

python - 从 postgreSQL 数据库(Django 站点)备份所有数据

python - 为什么要在检测文本之前 reshape MSER 轮廓?

python - 如何加载预训练的Word2vec模型文件?

python - 使用 shell=True w/list 时忽略 subprocess.call() 参数