本文介绍了在 Python 中添加简洁的向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常做 Python 列表的向量加法.

I often do vector addition of Python lists.

示例:我有两个这样的列表:

Example: I have two lists like these:

a = [0.0, 1.0, 2.0]
b = [3.0, 4.0, 5.0]

我现在想将 b 添加到 a 以获得结果 a = [3.0, 5.0, 7.0].

I now want to add b to a to get the result a = [3.0, 5.0, 7.0].

通常我会这样做:

a[0] += b[0]
a[1] += b[1]
a[2] += b[2]

是否有一些有效的标准方法可以减少输入次数?

Is there some efficient, standard way to do this with less typing?

更新:可以假设列表的长度为 3 并且包含浮点数.

UPDATE: It can be assumed that the lists are of length 3 and contain floats.

推荐答案

我认为您找不到比问题中提出的 3 个总和更快的解决方案.numpy 的优势在更大的向量中是可见的,如果你需要其他运算符也是如此.numpy 对矩阵特别有用,女巫是处理 python 列表的技巧.

I don't think you will find a faster solution than the 3 sums proposed in the question. The advantages of numpy are visible with larger vectors, and also if you need other operators. numpy is specially useful with matrixes, witch are trick to do with python lists.

仍然是另一种方法:D

In [1]: a = [1,2,3]

In [2]: b = [2,3,4]

In [3]: map(sum, zip(a,b))
Out[3]: [3, 5, 7]

编辑:您还可以使用 itertools 中的 izip,它是 zip 的生成器版本

Edit: you can also use the izip from itertools, a generator version of zip

In [5]: from itertools import izip

In [6]: map(sum, izip(a,b))
Out[6]: [3, 5, 7]

这篇关于在 Python 中添加简洁的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:02