标签归档:elementwise-operations

如何执行两个列表的按元素相乘?

问题:如何执行两个列表的按元素相乘?

我想执行元素明智的乘法,将两个列表按值在Python中相乘,就像我们在Matlab中可以做到的那样。

这就是我在Matlab中要做的。

a = [1,2,3,4]
b = [2,3,4,5]
a .* b = [2, 6, 12, 20]

对于from 和from的每个组合x * y,列表理解将给出16个列表条目。不确定如何映射。xayb

如果有人对此感兴趣,我有一个数据集,并想乘以Numpy.linspace(1.0, 0.5, num=len(dataset)) =)

I want to perform an element wise multiplication, to multiply two lists together by value in Python, like we can do it in Matlab.

This is how I would do it in Matlab.

a = [1,2,3,4]
b = [2,3,4,5]
a .* b = [2, 6, 12, 20]

A list comprehension would give 16 list entries, for every combination x * y of x from a and y from b. Unsure of how to map this.

If anyone is interested why, I have a dataset, and want to multiply it by Numpy.linspace(1.0, 0.5, num=len(dataset)) =).


回答 0

使用列表理解与zip():混合。

[a*b for a,b in zip(lista,listb)]

Use a list comprehension mixed with zip():.

[a*b for a,b in zip(lista,listb)]

回答 1

由于您已经在使用numpy,因此将数据存储在numpy数组而不是列表中很有意义。完成此操作后,您将免费获得类似智能元素的产品:

In [1]: import numpy as np

In [2]: a = np.array([1,2,3,4])

In [3]: b = np.array([2,3,4,5])

In [4]: a * b
Out[4]: array([ 2,  6, 12, 20])

Since you’re already using numpy, it makes sense to store your data in a numpy array rather than a list. Once you do this, you get things like element-wise products for free:

In [1]: import numpy as np

In [2]: a = np.array([1,2,3,4])

In [3]: b = np.array([2,3,4,5])

In [4]: a * b
Out[4]: array([ 2,  6, 12, 20])

回答 2

使用np.multiply(a,b):

import numpy as np
a = [1,2,3,4]
b = [2,3,4,5]
np.multiply(a,b)

Use np.multiply(a,b):

import numpy as np
a = [1,2,3,4]
b = [2,3,4,5]
np.multiply(a,b)

回答 3

您可以尝试将每个元素乘以一个循环。这样做的捷径是

ab = [a[i]*b[i] for i in range(len(a))]

You can try multiplying each element in a loop. The short hand for doing that is

ab = [a[i]*b[i] for i in range(len(a))]

回答 4

还有一个答案:

-1…需要导入
+1…非常易读

import operator
a = [1,2,3,4]
b = [10,11,12,13]

list(map(operator.mul, a, b))

输出[10、22、36、52]

Yet another answer:

-1 … requires import
+1 … is very readable

import operator
a = [1,2,3,4]
b = [10,11,12,13]

list(map(operator.mul, a, b))

outputs [10, 22, 36, 52]


回答 5

相当直观的方法:

a = [1,2,3,4]
b = [2,3,4,5]
ab = []                        #Create empty list
for i in range(0, len(a)):
     ab.append(a[i]*b[i])      #Adds each element to the list

Fairly intuitive way of doing this:

a = [1,2,3,4]
b = [2,3,4,5]
ab = []                        #Create empty list
for i in range(0, len(a)):
     ab.append(a[i]*b[i])      #Adds each element to the list

回答 6

您可以使用 lambda

foo=[1,2,3,4]
bar=[1,2,5,55]
l=map(lambda x,y:x*y,foo,bar)

you can multiplication using lambda

foo=[1,2,3,4]
bar=[1,2,5,55]
l=map(lambda x,y:x*y,foo,bar)

回答 7

对于大型列表,我们可以反复进行:

product_iter_object = itertools.imap(operator.mul, [1,2,3,4], [2,3,4,5])

product_iter_object.next() 给出输出列表中的每个元素。

输出将是两个输入列表中较短者的长度。

For large lists, we can do it the iter-way:

product_iter_object = itertools.imap(operator.mul, [1,2,3,4], [2,3,4,5])

product_iter_object.next() gives each of the element in the output list.

The output would be the length of the shorter of the two input lists.


回答 8

创建一个数组;将每个列表乘以数组;将数组转换为列表

import numpy as np

a = [1,2,3,4]
b = [2,3,4,5]

c = (np.ones(len(a))*a*b).tolist()

[2.0, 6.0, 12.0, 20.0]

create an array of ones; multiply each list times the array; convert array to a list

import numpy as np

a = [1,2,3,4]
b = [2,3,4,5]

c = (np.ones(len(a))*a*b).tolist()

[2.0, 6.0, 12.0, 20.0]

回答 9

gahooa的答案对于标题中所述的问题是正确的,但是如果列表已经是numpy格式大于十,它将更快(3个数量级)并且可读性更高,如NPE。我得到这些时间:

0.0049ms -> N = 4, a = [i for i in range(N)], c = [a*b for a,b in zip(a, b)]
0.0075ms -> N = 4, a = [i for i in range(N)], c = a * b
0.0167ms -> N = 4, a = np.arange(N), c = [a*b for a,b in zip(a, b)]
0.0013ms -> N = 4, a = np.arange(N), c = a * b
0.0171ms -> N = 40, a = [i for i in range(N)], c = [a*b for a,b in zip(a, b)]
0.0095ms -> N = 40, a = [i for i in range(N)], c = a * b
0.1077ms -> N = 40, a = np.arange(N), c = [a*b for a,b in zip(a, b)]
0.0013ms -> N = 40, a = np.arange(N), c = a * b
0.1485ms -> N = 400, a = [i for i in range(N)], c = [a*b for a,b in zip(a, b)]
0.0397ms -> N = 400, a = [i for i in range(N)], c = a * b
1.0348ms -> N = 400, a = np.arange(N), c = [a*b for a,b in zip(a, b)]
0.0020ms -> N = 400, a = np.arange(N), c = a * b

即从以下测试程序。

import timeit

init = ['''
import numpy as np
N = {}
a = {}
b = np.linspace(0.0, 0.5, len(a))
'''.format(i, j) for i in [4, 40, 400] 
                  for j in ['[i for i in range(N)]', 'np.arange(N)']]

func = ['''c = [a*b for a,b in zip(a, b)]''',
'''c = a * b''']

for i in init:
  for f in func:
    lines = i.split('\n')
    print('{:6.4f}ms -> {}, {}, {}'.format(
           timeit.timeit(f, setup=i, number=1000), lines[2], lines[3], f))

gahooa’s answer is correct for the question as phrased in the heading, but if the lists are already numpy format or larger than ten it will be MUCH faster (3 orders of magnitude) as well as more readable, to do simple numpy multiplication as suggested by NPE. I get these timings:

0.0049ms -> N = 4, a = [i for i in range(N)], c = [a*b for a,b in zip(a, b)]
0.0075ms -> N = 4, a = [i for i in range(N)], c = a * b
0.0167ms -> N = 4, a = np.arange(N), c = [a*b for a,b in zip(a, b)]
0.0013ms -> N = 4, a = np.arange(N), c = a * b
0.0171ms -> N = 40, a = [i for i in range(N)], c = [a*b for a,b in zip(a, b)]
0.0095ms -> N = 40, a = [i for i in range(N)], c = a * b
0.1077ms -> N = 40, a = np.arange(N), c = [a*b for a,b in zip(a, b)]
0.0013ms -> N = 40, a = np.arange(N), c = a * b
0.1485ms -> N = 400, a = [i for i in range(N)], c = [a*b for a,b in zip(a, b)]
0.0397ms -> N = 400, a = [i for i in range(N)], c = a * b
1.0348ms -> N = 400, a = np.arange(N), c = [a*b for a,b in zip(a, b)]
0.0020ms -> N = 400, a = np.arange(N), c = a * b

i.e. from the following test program.

import timeit

init = ['''
import numpy as np
N = {}
a = {}
b = np.linspace(0.0, 0.5, len(a))
'''.format(i, j) for i in [4, 40, 400] 
                  for j in ['[i for i in range(N)]', 'np.arange(N)']]

func = ['''c = [a*b for a,b in zip(a, b)]''',
'''c = a * b''']

for i in init:
  for f in func:
    lines = i.split('\n')
    print('{:6.4f}ms -> {}, {}, {}'.format(
           timeit.timeit(f, setup=i, number=1000), lines[2], lines[3], f))

回答 10

可以使用枚举。

a = [1, 2, 3, 4]
b = [2, 3, 4, 5]

ab = [val * b[i] for i, val in enumerate(a)]

Can use enumerate.

a = [1, 2, 3, 4]
b = [2, 3, 4, 5]

ab = [val * b[i] for i, val in enumerate(a)]

回答 11

map功能在这里可能非常有用。使用map我们可以将任何函数应用于可迭代对象的每个元素。

Python 3.x

>>> def my_mul(x,y):
...     return x*y
...
>>> a = [1,2,3,4]
>>> b = [2,3,4,5]
>>>
>>> list(map(my_mul,a,b))
[2, 6, 12, 20]
>>>

当然:

map(f, iterable)

相当于

[f(x) for x in iterable]

因此,我们可以通过以下方式获得解决方案:

>>> [my_mul(x,y) for x, y in zip(a,b)]
[2, 6, 12, 20]
>>>

在Python 2.x中map()意味着:将函数应用于可迭代的每个元素并构造一个新列表。在Python 3.x中,map构造迭代器而不是列表。

代替my_mul我们可以使用 mul运算符

Python 2.7

>>>from operator import mul # import mul operator
>>>a = [1,2,3,4]
>>>b = [2,3,4,5]
>>>map(mul,a,b)
[2, 6, 12, 20]
>>>

Python 3.5+

>>> from operator import mul
>>> a = [1,2,3,4]
>>> b = [2,3,4,5]
>>> [*map(mul,a,b)]
[2, 6, 12, 20]
>>>

请注意,由于map()构造了迭代器,因此我们使用*可迭代的拆包运算符来获取列表。解压缩方法比list构造函数要快一些:

>>> list(map(mul,a,b))
[2, 6, 12, 20]
>>>

The map function can be very useful here. Using map we can apply any function to each element of an iterable.

Python 3.x

>>> def my_mul(x,y):
...     return x*y
...
>>> a = [1,2,3,4]
>>> b = [2,3,4,5]
>>>
>>> list(map(my_mul,a,b))
[2, 6, 12, 20]
>>>

Of course:

map(f, iterable)

is equivalent to

[f(x) for x in iterable]

So we can get our solution via:

>>> [my_mul(x,y) for x, y in zip(a,b)]
[2, 6, 12, 20]
>>>

In Python 2.x map() means: apply a function to each element of an iterable and construct a new list. In Python 3.x, map construct iterators instead of lists.

Instead of my_mul we could use mul operator

Python 2.7

>>>from operator import mul # import mul operator
>>>a = [1,2,3,4]
>>>b = [2,3,4,5]
>>>map(mul,a,b)
[2, 6, 12, 20]
>>>

Python 3.5+

>>> from operator import mul
>>> a = [1,2,3,4]
>>> b = [2,3,4,5]
>>> [*map(mul,a,b)]
[2, 6, 12, 20]
>>>

Please note that since map() constructs an iterator we use * iterable unpacking operator to get a list. The unpacking approach is a bit faster then the list constructor:

>>> list(map(mul,a,b))
[2, 6, 12, 20]
>>>

回答 12

要维护列表类型,并在一行中完成(当然,在将numpy导入为np之后):

list(np.array([1,2,3,4]) * np.array([2,3,4,5]))

要么

list(np.array(a) * np.array(b))

To maintain the list type, and do it in one line (after importing numpy as np, of course):

list(np.array([1,2,3,4]) * np.array([2,3,4,5]))

or

list(np.array(a) * np.array(b))

回答 13

您可以将其用于相同长度的列表

def lstsum(a, b):
    c=0
    pos = 0
for element in a:
   c+= element*b[pos]
   pos+=1
return c

you can use this for lists of the same length

def lstsum(a, b):
    c=0
    pos = 0
for element in a:
   c+= element*b[pos]
   pos+=1
return c

如何在numpy中获得按元素矩阵乘法(Hadamard积)?

问题:如何在numpy中获得按元素矩阵乘法(Hadamard积)?

我有两个矩阵

a = np.matrix([[1,2], [3,4]])
b = np.matrix([[5,6], [7,8]])

我想得到元素乘积[[1*5,2*6], [3*7,4*8]],等于

[[5,12], [21,32]]

我努力了

print(np.dot(a,b)) 

print(a*b)

但两者都给出结果

[[19 22], [43 50]]

这是矩阵乘积,而不是元素乘积。如何使用内置函数获取按元素分类的产品(又名Hadamard产品)?

I have two matrices

a = np.matrix([[1,2], [3,4]])
b = np.matrix([[5,6], [7,8]])

and I want to get the element-wise product, [[1*5,2*6], [3*7,4*8]], equaling

[[5,12], [21,32]]

I have tried

print(np.dot(a,b)) 

and

print(a*b)

but both give the result

[[19 22], [43 50]]

which is the matrix product, not the element-wise product. How can I get the the element-wise product (aka Hadamard product) using built-in functions?


回答 0

对于matrix对象的元素乘法,可以使用numpy.multiply

import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
np.multiply(a,b)

结果

array([[ 5, 12],
       [21, 32]])

但是,您应该真正使用array而不是matrixmatrix对象与常规ndarray具有各种可怕的不兼容性。使用ndarrays时,您可以仅使用*元素级乘法:

a * b

如果您使用的是Python 3.5+,则您甚至都不会失去使用运算符执行矩阵乘法的能力,因为@矩阵乘法现在可以

a @ b  # matrix multiplication

For elementwise multiplication of matrix objects, you can use numpy.multiply:

import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
np.multiply(a,b)

Result

array([[ 5, 12],
       [21, 32]])

However, you should really use array instead of matrix. matrix objects have all sorts of horrible incompatibilities with regular ndarrays. With ndarrays, you can just use * for elementwise multiplication:

a * b

If you’re on Python 3.5+, you don’t even lose the ability to perform matrix multiplication with an operator, because @ does matrix multiplication now:

a @ b  # matrix multiplication

回答 1

只是这样做:

import numpy as np

a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])

a * b

just do this:

import numpy as np

a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])

a * b

回答 2

import numpy as np
x = np.array([[1,2,3], [4,5,6]])
y = np.array([[-1, 2, 0], [-2, 5, 1]])

x*y
Out: 
array([[-1,  4,  0],
       [-8, 25,  6]])

%timeit x*y
1000000 loops, best of 3: 421 ns per loop

np.multiply(x,y)
Out: 
array([[-1,  4,  0],
       [-8, 25,  6]])

%timeit np.multiply(x, y)
1000000 loops, best of 3: 457 ns per loop

两者np.multiply*都会产生元素明智的乘法,称为Hadamard积

%timeit 是ipython的魔力

import numpy as np
x = np.array([[1,2,3], [4,5,6]])
y = np.array([[-1, 2, 0], [-2, 5, 1]])

x*y
Out: 
array([[-1,  4,  0],
       [-8, 25,  6]])

%timeit x*y
1000000 loops, best of 3: 421 ns per loop

np.multiply(x,y)
Out: 
array([[-1,  4,  0],
       [-8, 25,  6]])

%timeit np.multiply(x, y)
1000000 loops, best of 3: 457 ns per loop

Both np.multiply and * would yield element wise multiplication known as the Hadamard Product

%timeit is ipython magic


回答 3

试试这个:

a = np.matrix([[1,2], [3,4]])
b = np.matrix([[5,6], [7,8]])

#This would result a 'numpy.ndarray'
result = np.array(a) * np.array(b)

在此,np.array(a)返回类型为2D的2D数组,ndarray并且ndarray将导致元素相乘。因此结果将是:

result = [[5, 12], [21, 32]]

如果您想获取矩阵,请执行以下操作:

result = np.mat(result)

Try this:

a = np.matrix([[1,2], [3,4]])
b = np.matrix([[5,6], [7,8]])

#This would result a 'numpy.ndarray'
result = np.array(a) * np.array(b)

Here, np.array(a) returns a 2D array of type ndarray and multiplication of two ndarray would result element wise multiplication. So the result would be:

result = [[5, 12], [21, 32]]

If you wanna get a matrix, the do it with this:

result = np.mat(result)

比较两个NumPy数组的相等性,按元素

问题:比较两个NumPy数组的相等性,按元素

比较两个NumPy数组是否相等的最简单方法是什么(其中相等定义为:对于所有索引i:,A = B iff A[i] == B[i])?

简单地使用==给我一个布尔数组:

 >>> numpy.array([1,1,1]) == numpy.array([1,1,1])

array([ True,  True,  True], dtype=bool)

是否and需要确定该数组的元素是否相等,或者是否有更简单的比较方法?

What is the simplest way to compare two NumPy arrays for equality (where equality is defined as: A = B iff for all indices i: A[i] == B[i])?

Simply using == gives me a boolean array:

 >>> numpy.array([1,1,1]) == numpy.array([1,1,1])

array([ True,  True,  True], dtype=bool)

Do I have to and the elements of this array to determine if the arrays are equal, or is there a simpler way to compare?


回答 0

(A==B).all()

测试数组(A == B)的所有值是否均为True。

注意:也许您还想测试A和B形状,例如 A.shape == B.shape

特殊情况和替代方法(来自dbaupp的回答和yoavram的评论)

应当指出的是:

  • 在特定情况下,此解决方案可能会产生奇怪的行为:如果AB为空且另一个包含单个元素,则返回True。由于某种原因,比较会A==B返回一个空数组,all操作员将为此返回一个空数组True
  • 另一个风险是,如果AB形状不相同且不可广播,则此方法将引发错误。

总之,如果你有一个关于怀疑AB形状或只是想安全:的专业功能用途之一:

np.array_equal(A,B)  # test if same shape, same elements values
np.array_equiv(A,B)  # test if broadcastable shape, same elements values
np.allclose(A,B,...) # test if same shape, elements have close enough values
(A==B).all()

test if all values of array (A==B) are True.

Note: maybe you also want to test A and B shape, such as A.shape == B.shape

Special cases and alternatives (from dbaupp’s answer and yoavram’s comment)

It should be noted that:

  • this solution can have a strange behavior in a particular case: if either A or B is empty and the other one contains a single element, then it return True. For some reason, the comparison A==B returns an empty array, for which the all operator returns True.
  • Another risk is if A and B don’t have the same shape and aren’t broadcastable, then this approach will raise an error.

In conclusion, if you have a doubt about A and B shape or simply want to be safe: use one of the specialized functions:

np.array_equal(A,B)  # test if same shape, same elements values
np.array_equiv(A,B)  # test if broadcastable shape, same elements values
np.allclose(A,B,...) # test if same shape, elements have close enough values

回答 1

(A==B).all()解决方案是很整齐,但也有完成这个任务的一些内置的功能。也就是说array_equalallclosearray_equiv

(尽管,使用进行一些快速测试timeit似乎表明该(A==B).all()方法是最快的,由于必须分配一个全新的数组,因此该方法有点特殊。)

The (A==B).all() solution is very neat, but there are some built-in functions for this task. Namely array_equal, allclose and array_equiv.

(Although, some quick testing with timeit seems to indicate that the (A==B).all() method is the fastest, which is a little peculiar, given it has to allocate a whole new array.)


回答 2

让我们通过使用以下代码来评估性能。

import numpy as np
import time

exec_time0 = []
exec_time1 = []
exec_time2 = []

sizeOfArray = 5000
numOfIterations = 200

for i in xrange(numOfIterations):

    A = np.random.randint(0,255,(sizeOfArray,sizeOfArray))
    B = np.random.randint(0,255,(sizeOfArray,sizeOfArray))

    a = time.clock() 
    res = (A==B).all()
    b = time.clock()
    exec_time0.append( b - a )

    a = time.clock() 
    res = np.array_equal(A,B)
    b = time.clock()
    exec_time1.append( b - a )

    a = time.clock() 
    res = np.array_equiv(A,B)
    b = time.clock()
    exec_time2.append( b - a )

print 'Method: (A==B).all(),       ', np.mean(exec_time0)
print 'Method: np.array_equal(A,B),', np.mean(exec_time1)
print 'Method: np.array_equiv(A,B),', np.mean(exec_time2)

输出量

Method: (A==B).all(),        0.03031857
Method: np.array_equal(A,B), 0.030025185
Method: np.array_equiv(A,B), 0.030141515

根据上面的结果,numpy方法似乎比==运算符和all()方法的组合要快,并且通过比较numpy方法,最快的方法似乎是numpy.array_equal方法。

Let’s measure the performance by using the following piece of code.

import numpy as np
import time

exec_time0 = []
exec_time1 = []
exec_time2 = []

sizeOfArray = 5000
numOfIterations = 200

for i in xrange(numOfIterations):

    A = np.random.randint(0,255,(sizeOfArray,sizeOfArray))
    B = np.random.randint(0,255,(sizeOfArray,sizeOfArray))

    a = time.clock() 
    res = (A==B).all()
    b = time.clock()
    exec_time0.append( b - a )

    a = time.clock() 
    res = np.array_equal(A,B)
    b = time.clock()
    exec_time1.append( b - a )

    a = time.clock() 
    res = np.array_equiv(A,B)
    b = time.clock()
    exec_time2.append( b - a )

print 'Method: (A==B).all(),       ', np.mean(exec_time0)
print 'Method: np.array_equal(A,B),', np.mean(exec_time1)
print 'Method: np.array_equiv(A,B),', np.mean(exec_time2)

Output

Method: (A==B).all(),        0.03031857
Method: np.array_equal(A,B), 0.030025185
Method: np.array_equiv(A,B), 0.030141515

According to the results above, the numpy methods seem to be faster than the combination of the == operator and the all() method and by comparing the numpy methods the fastest one seems to be the numpy.array_equal method.


回答 3

如果要检查两个数组是否相同shape并且elements应该使用,np.array_equal因为这是文档中建议的方法。

在性能方面,不要期望任何相等性检查会胜过另一个,因为没有太多的优化空间comparing two elements。为了方便起见,我仍然进行了一些测试。

import numpy as np
import timeit

A = np.zeros((300, 300, 3))
B = np.zeros((300, 300, 3))
C = np.ones((300, 300, 3))

timeit.timeit(stmt='(A==B).all()', setup='from __main__ import A, B', number=10**5)
timeit.timeit(stmt='np.array_equal(A, B)', setup='from __main__ import A, B, np', number=10**5)
timeit.timeit(stmt='np.array_equiv(A, B)', setup='from __main__ import A, B, np', number=10**5)
> 51.5094
> 52.555
> 52.761

几乎相等,无需谈论速度。

(A==B).all()的行为几乎如下面的代码片段:

x = [1,2,3]
y = [1,2,3]
print all([x[i]==y[i] for i in range(len(x))])
> True

If you want to check if two arrays have the same shape AND elements you should use np.array_equal as it is the method recommended in the documentation.

Performance-wise don’t expect that any equality check will beat another, as there is not much room to optimize comparing two elements. Just for the sake, i still did some tests.

import numpy as np
import timeit

A = np.zeros((300, 300, 3))
B = np.zeros((300, 300, 3))
C = np.ones((300, 300, 3))

timeit.timeit(stmt='(A==B).all()', setup='from __main__ import A, B', number=10**5)
timeit.timeit(stmt='np.array_equal(A, B)', setup='from __main__ import A, B, np', number=10**5)
timeit.timeit(stmt='np.array_equiv(A, B)', setup='from __main__ import A, B, np', number=10**5)
> 51.5094
> 52.555
> 52.761

So pretty much equal, no need to talk about the speed.

The (A==B).all() behaves pretty much as the following code snippet:

x = [1,2,3]
y = [1,2,3]
print all([x[i]==y[i] for i in range(len(x))])
> True

回答 4

通常两个数组会有一些小的数字误差,

您可以使用numpy.allclose(A,B)代替(A==B).all()。这将返回布尔值True / False

Usually two arrays will have some small numeric errors,

You can use numpy.allclose(A,B), instead of (A==B).all(). This returns a bool True/False


回答 5

现在使用np.array_equal。从文档:

np.array_equal([1, 2], [1, 2])
True
np.array_equal(np.array([1, 2]), np.array([1, 2]))
True
np.array_equal([1, 2], [1, 2, 3])
False
np.array_equal([1, 2], [1, 4])
False

Now use np.array_equal. From documentation:

np.array_equal([1, 2], [1, 2])
True
np.array_equal(np.array([1, 2]), np.array([1, 2]))
True
np.array_equal([1, 2], [1, 2, 3])
False
np.array_equal([1, 2], [1, 4])
False

按元素添加2个列表?

问题:按元素添加2个列表?

我现在有了:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

我希望有:

[1, 2, 3]
 +  +  +
[4, 5, 6]
|| || ||
[5, 7, 9]

只是两个列表的逐个元素相加。

我当然可以迭代这两个列表,但是我不想这样做。

什么是最Python的方式这样做的?

I have now:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

I wish to have:

[1, 2, 3]
 +  +  +
[4, 5, 6]
|| || ||
[5, 7, 9]

Simply an element-wise addition of two lists.

I can surely iterate the two lists, but I don’t want do that.

What is the most Pythonic way of doing so?


回答 0

使用mapoperator.add

>>> from operator import add
>>> list( map(add, list1, list2) )
[5, 7, 9]

zip具有列表理解:

>>> [sum(x) for x in zip(list1, list2)]
[5, 7, 9]

时序比较:

>>> list2 = [4, 5, 6]*10**5
>>> list1 = [1, 2, 3]*10**5
>>> %timeit from operator import add;map(add, list1, list2)
10 loops, best of 3: 44.6 ms per loop
>>> %timeit from itertools import izip; [a + b for a, b in izip(list1, list2)]
10 loops, best of 3: 71 ms per loop
>>> %timeit [a + b for a, b in zip(list1, list2)]
10 loops, best of 3: 112 ms per loop
>>> %timeit from itertools import izip;[sum(x) for x in izip(list1, list2)]
1 loops, best of 3: 139 ms per loop
>>> %timeit [sum(x) for x in zip(list1, list2)]
1 loops, best of 3: 177 ms per loop

Use map with operator.add:

>>> from operator import add
>>> list( map(add, list1, list2) )
[5, 7, 9]

or zip with a list comprehension:

>>> [sum(x) for x in zip(list1, list2)]
[5, 7, 9]

Timing comparisons:

>>> list2 = [4, 5, 6]*10**5
>>> list1 = [1, 2, 3]*10**5
>>> %timeit from operator import add;map(add, list1, list2)
10 loops, best of 3: 44.6 ms per loop
>>> %timeit from itertools import izip; [a + b for a, b in izip(list1, list2)]
10 loops, best of 3: 71 ms per loop
>>> %timeit [a + b for a, b in zip(list1, list2)]
10 loops, best of 3: 112 ms per loop
>>> %timeit from itertools import izip;[sum(x) for x in izip(list1, list2)]
1 loops, best of 3: 139 ms per loop
>>> %timeit [sum(x) for x in zip(list1, list2)]
1 loops, best of 3: 177 ms per loop

回答 1

其他人给出了如何在纯python中执行此操作的示例。如果要对具有100.000个元素的数组执行此操作,则应使用numpy:

In [1]: import numpy as np
In [2]: vector1 = np.array([1, 2, 3])
In [3]: vector2 = np.array([4, 5, 6])

现在,按元素进行加法与

In [4]: sum_vector = vector1 + vector2
In [5]: print sum_vector
[5 7 9]

就像在Matlab中一样。

与Ashwini最快版本进行比较的时间:

In [16]: from operator import add
In [17]: n = 10**5
In [18]: vector2 = np.tile([4,5,6], n)
In [19]: vector1 = np.tile([1,2,3], n)
In [20]: list1 = [1,2,3]*n
In [21]: list2 = [4,5,6]*n
In [22]: timeit map(add, list1, list2)
10 loops, best of 3: 26.9 ms per loop

In [23]: timeit vector1 + vector2
1000 loops, best of 3: 1.06 ms per loop

因此这快25倍!但是请使用适合您情况的东西。对于一个简单的程序,您可能不想安装numpy,因此请使用标准python(我发现Henry的版本是最Pythonic 的版本)。如果您正认真处理数字,numpy那么就进行繁重的工作。对于速度怪胎:似乎numpy解决方案的运行速度更快n = 8

The others gave examples how to do this in pure python. If you want to do this with arrays with 100.000 elements, you should use numpy:

In [1]: import numpy as np
In [2]: vector1 = np.array([1, 2, 3])
In [3]: vector2 = np.array([4, 5, 6])

Doing the element-wise addition is now as trivial as

In [4]: sum_vector = vector1 + vector2
In [5]: print sum_vector
[5 7 9]

just like in Matlab.

Timing to compare with Ashwini’s fastest version:

In [16]: from operator import add
In [17]: n = 10**5
In [18]: vector2 = np.tile([4,5,6], n)
In [19]: vector1 = np.tile([1,2,3], n)
In [20]: list1 = [1,2,3]*n
In [21]: list2 = [4,5,6]*n
In [22]: timeit map(add, list1, list2)
10 loops, best of 3: 26.9 ms per loop

In [23]: timeit vector1 + vector2
1000 loops, best of 3: 1.06 ms per loop

So this is a factor 25 faster! But use what suits your situation. For a simple program, you probably don’t want to install numpy, so use standard python (and I find Henry’s version the most Pythonic one). If you are into serious number crunching, let numpy do the heavy lifting. For the speed freaks: it seems that the numpy solution is faster starting around n = 8.


回答 2

[a + b for a, b in zip(list1, list2)]
[a + b for a, b in zip(list1, list2)]

回答 3

如其他人所述,一种快速且节省空间的解决方案是使用numpy(np)及其内置的矢量处理功能:

1.脾气暴躁

x = np.array([1,2,3])
y = np.array([2,3,4])
print x+y

2.内置

2.1 Lambda

list1=[1, 2, 3]
list2=[4, 5, 6]
print map(lambda x,y:x+y, list1, list2)

注意,map()支持多个参数。

2.2 zip和列表理解

list1=[1, 2, 3]
list2=[4, 5, 6]
print [x + y for x, y in zip(list1, list2)]

As described by others, a fast and also space efficient solution is using numpy (np) with it’s built-in vector manipulation capability:

1. With Numpy

x = np.array([1,2,3])
y = np.array([2,3,4])
print x+y

2. With built-ins

2.1 Lambda

list1=[1, 2, 3]
list2=[4, 5, 6]
print map(lambda x,y:x+y, list1, list2)

Notice that map() supports multiple arguments.

2.2 zip and list comprehension

list1=[1, 2, 3]
list2=[4, 5, 6]
print [x + y for x, y in zip(list1, list2)]

回答 4

numpy我认为使用起来更简单:

import numpy as np
list1=[1,2,3]
list2=[4,5,6]
np.add(list1,list2)

结果:

有关详细的参数信息,请在此处检查:numpy.add

It’s simpler to use numpy from my opinion:

import numpy as np
list1=[1,2,3]
list2=[4,5,6]
np.add(list1,list2)

Results:

For detailed parameter information, check here: numpy.add


回答 5

也许“最Python的方式”应该包括处理list1和list2大小不相同的情况。应用其中一些方法会悄悄地为您提供答案。numpy方法会让您知道,很可能是发生ValueError。

例:

import numpy as np
>>> list1 = [ 1, 2 ]
>>> list2 = [ 1, 2, 3]
>>> list3 = [ 1 ]
>>> [a + b for a, b in zip(list1, list2)]
[2, 4]
>>> [a + b for a, b in zip(list1, list3)]
[2]
>>> a = np.array (list1)
>>> b = np.array (list2)
>>> a+b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (2) (3)

如果这在您的问题中起作用,您可能想要哪个结果?

Perhaps “the most pythonic way” should include handling the case where list1 and list2 are not the same size. Applying some of these methods will quietly give you an answer. The numpy approach will let you know, most likely with a ValueError.

Example:

import numpy as np
>>> list1 = [ 1, 2 ]
>>> list2 = [ 1, 2, 3]
>>> list3 = [ 1 ]
>>> [a + b for a, b in zip(list1, list2)]
[2, 4]
>>> [a + b for a, b in zip(list1, list3)]
[2]
>>> a = np.array (list1)
>>> b = np.array (list2)
>>> a+b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (2) (3)

Which result might you want if this were in a function in your problem?


回答 6

这很简单 numpy.add()

import numpy

list1 = numpy.array([1, 2, 3])
list2 = numpy.array([4, 5, 6])
result = numpy.add(list1, list2) # result receive element-wise addition of list1 and list2
print(result)
array([5, 7, 9])

在这里查看文档

如果要接收python列表:

result.tolist()

This is simple with numpy.add()

import numpy

list1 = numpy.array([1, 2, 3])
list2 = numpy.array([4, 5, 6])
result = numpy.add(list1, list2) # result receive element-wise addition of list1 and list2
print(result)
array([5, 7, 9])

See doc here

If you want to receiver a python list:

result.tolist()

回答 7

这将适用于2个或更多列表;遍历列表列表,但使用numpy加法处理每个列表的元素

import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]

lists = [list1, list2]
list_sum = np.zeros(len(list1))
for i in lists:
   list_sum += i
list_sum = list_sum.tolist()    

[5.0, 7.0, 9.0]

This will work for 2 or more lists; iterating through the list of lists, but using numpy addition to deal with elements of each list

import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]

lists = [list1, list2]
list_sum = np.zeros(len(list1))
for i in lists:
   list_sum += i
list_sum = list_sum.tolist()    

[5.0, 7.0, 9.0]

回答 8

也许这是pythonic的,如果列表数量未知且未导入任何内容,则稍微有用。

只要列表的长度相同,就可以使用以下功能。

在这里,* args接受可变数量的列表参数(但每个参数仅求和相同数量的元素)。

在返回的列表中再次使用*来解压缩每个列表中的元素。

def sum_lists(*args):
    return list(map(sum, zip(*args)))

a = [1,2,3]
b = [1,2,3]  

sum_lists(a,b)

输出:

[2, 4, 6]

或有3个清单

sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])

输出:

[19, 19, 19, 19, 19]

Perhaps this is pythonic and slightly useful if you have an unknown number of lists, and without importing anything.

As long as the lists are of the same length, you can use the below function.

Here the *args accepts a variable number of list arguments (but only sums the same number of elements in each).

The * is used again in the returned list to unpack the elements in each of the lists.

def sum_lists(*args):
    return list(map(sum, zip(*args)))

a = [1,2,3]
b = [1,2,3]  

sum_lists(a,b)

Output:

[2, 4, 6]

Or with 3 lists

sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])

Output:

[19, 19, 19, 19, 19]

回答 9

将地图与lambda函数一起使用:

>>> map(lambda x, y: x + y, list1, list2)
[5, 7, 9]

Use map with lambda function:

>>> map(lambda x, y: x + y, list1, list2)
[5, 7, 9]

回答 10

我尚未计时,但我怀疑这会很快:

import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]

list_sum = (np.add(list1, list2)).tolist()

[5, 7, 9]

I haven’t timed it but I suspect this would be pretty quick:

import numpy as np
list1=[1, 2, 3]
list2=[4, 5, 6]

list_sum = (np.add(list1, list2)).tolist()

[5, 7, 9]

回答 11

如果您需要处理不同大小的列表,请不用担心!精彩的itertools模块涵盖了:

>>> from itertools import zip_longest
>>> list1 = [1,2,1]
>>> list2 = [2,1,2,3]
>>> [sum(x) for x in zip_longest(list1, list2, fillvalue=0)]
[3, 3, 3, 3]
>>>

在Python 2中,zip_longest称为izip_longest

另请参阅此相关答案并评论另一个问题

If you need to handle lists of different sizes, worry not! The wonderful itertools module has you covered:

>>> from itertools import zip_longest
>>> list1 = [1,2,1]
>>> list2 = [2,1,2,3]
>>> [sum(x) for x in zip_longest(list1, list2, fillvalue=0)]
[3, 3, 3, 3]
>>>

In Python 2, zip_longest is called izip_longest.

See also this relevant answer and comment on another question.


回答 12

[list1[i] + list2[i] for i in range(len(list1))]
[list1[i] + list2[i] for i in range(len(list1))]

回答 13

虽然,实际的问题并不想遍历列表来生成结果,但是已经提出的所有解决方案实际上都是在后台进行的!

刷新:如果不查看所有矢量元素,则不能添加两个矢量。因此,大多数这些解决方案的算法复杂度为Big-O(n)。其中n是向量的维数。

因此,从算法的角度来看,使用for循环迭代生成结果列表也是逻辑和pythonic的。但是,此外,此方法没有调用或导入任何其他库的开销。

# Assumption: The lists are of equal length.
resultList = [list1[i] + list2[i] for i in range(len(list1))]

这里显示/讨论的时间取决于系统和实现,并且不是测量操作效率的可靠措施。在任何情况下,向量加法运算的大O复杂度都是线性的,即O(n)。

Although, the actual question does not want to iterate over the list to generate the result, but all the solutions that has been proposed does exactly that under-neath the hood!

To refresh: You cannot add two vectors without looking into all the vector elements. So, the algorithmic complexity of most of these solutions are Big-O(n). Where n is the dimension of the vector.

So, from an algorithmic point of view, using a for loop to iteratively generate the resulting list is logical and pythonic too. However, in addition, this method does not have the overhead of calling or importing any additional library.

# Assumption: The lists are of equal length.
resultList = [list1[i] + list2[i] for i in range(len(list1))]

The timings that are being showed/discussed here are system and implementation dependent, and cannot be reliable measure to measure the efficiency of the operation. In any case, the big O complexity of the vector addition operation is linear, meaning O(n).


回答 14

a_list = []
b_list = []
for i in range(1,100):
    a_list.append(random.randint(1,100))

for i in range(1,100):
    a_list.append(random.randint(101,200))
[sum(x) for x in zip(a_list , b_list )]
a_list = []
b_list = []
for i in range(1,100):
    a_list.append(random.randint(1,100))

for i in range(1,100):
    a_list.append(random.randint(101,200))
[sum(x) for x in zip(a_list , b_list )]