[英]Subtract values in one list from corresponding values in another list
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.谢谢。
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)
Perhaps this could be usefull.也许这可能有用。
C = []
for i in range(len(A)):
difference = A[i] - B[i]
C.append(difference)
One liner:一个班轮:
A = [2, 4, 6, 8, 10]
B = [1, 3, 5, 7, 9]
[A[x]-B[x] for x in range(len(B))]
#output
[1, 1, 1, 1, 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.