[英]How do you subtract list a from list b in Python?
So I have 2 lists, say list a
and list b
where 所以我有2个列表,说列表a
和列表b
,其中
a = [9, 8, 7, 6]
b = [1, 2, 3, 4]
How would I go about subtracting the contents of b
from a
? 我将如何从a
减去b
的内容?
You can zip the two lists and subtract the subelements to create a new list: 您可以压缩两个列表并减去子元素以创建新列表:
zip(b,a) -> [(1, 9), (2, 8), (3, 7), (4, 6)]
a = [9, 8, 7, 6]
b = [1, 2, 3, 4]
print([y-x for x,y in zip(b,a)])
[8, 6, 4, 2]
If you want to change a
itself use enumerate subtracting elements at common indexes: 如果你想改变a
单独使用罗列的常用指标减去元素:
for ind,ele in enumerate(a):
a[ind] -= b[ind]
print(a)
[8, 6, 4, 2]
Or using numpy: 或使用numpy:
import numpy as np 将numpy导入为np
a = np.array([9, 8, 7, 6])
b = np.array([1, 2, 3, 4])
print(a - b)
[8 6 4 2]
You can use the map function and it's feature to support more than one iterable (the following assumes Python2): 您可以使用map函数及其功能来支持多个迭代(以下假设为Python2):
>>> a = [9, 8, 7, 6]
>>> b = [1, 2, 3, 4]
>>> map(lambda x,y: x-y, a, b)
[8, 6, 4, 2]
map
applies the first argument (which has to be a function) on all elements of the following arguments. map
将第一个参数(必须是一个函数)应用于以下参数的所有元素。 For example: 例如:
>>> from math import sqrt
>>> map(sqrt, [1,2,9])
[1.0, 1.4142135623730951, 3.0]
If you use more than two arguments, the function in the first parameter must take more parameters, because it is called with elements from each list: 如果使用两个以上的参数,则第一个参数中的函数必须采用更多的参数,因为每个列表中的元素都会调用该函数:
>>> from math import pow
>>> map(pow, [2,3,4], [2,3,4])
[4.0, 27.0, 256.0]
The result is 2^2, 3^3 and 4^4. 结果是2 ^ 2、3 ^ 3和4 ^ 4。
The lambda
in my example is just a shorter way to define the subtraction function, the following code would do the same: 在我的示例中, lambda
只是定义减法函数的一种较短方法,以下代码将执行相同的操作:
def sub(x,y):
return x-y
map(sub, a, b)
a=[1,2,3,4,5]
b=[9,8,7,6,4]
t=0
h=[]
lenA=len(a)
while lenA != t:
x=a[t]-b[t]
t=t+1
h.append(x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.