从另一个列表中的相应值中减去一个列表中的值 - Python

时间:2022-06-19 08:00:13

I have two lists:

我有两个清单:

A = [2, 4, 6, 8, 10]
B = [1, 3, 5, 7, 9]

How do I subtract each value in one list from the corresponding value in the other list and create a list such that:

如何从另一个列表中的相应值中减去一个列表中的每个值,并创建一个列表,以便:

C = [1, 1, 1, 1, 1]

Thanks.

谢谢。

2 个解决方案

#1


41  

The easiest way is to use a list comprehension

最简单的方法是使用列表理解

C = [a - b for a, b in zip(A, B)]

or map():

或map():

from operator import sub
C = map(sub, A, B)

#2


8  

Since you appear to be an engineering student, you'll probably want to get familiar with numpy. If you've got it installed, you can do

既然你似乎是一名工科学生,你可能想要熟悉numpy。如果你已安装它,你可以做到

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

#1


41  

The easiest way is to use a list comprehension

最简单的方法是使用列表理解

C = [a - b for a, b in zip(A, B)]

or map():

或map():

from operator import sub
C = map(sub, A, B)

#2


8  

Since you appear to be an engineering student, you'll probably want to get familiar with numpy. If you've got it installed, you can do

既然你似乎是一名工科学生,你可能想要熟悉numpy。如果你已安装它,你可以做到

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