简体   繁体   English

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

[英]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)

Since you appear to be an engineering student, you'll probably want to get familiar with numpy .由于您似乎是一名工程专业的学生,​​因此您可能想要熟悉numpy If you've got it installed, you can do如果你已经安装了它,你可以做

>>> 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]

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.

相关问题 如何从一个列表中删除特定值以及另一个列表中的相应值 - How to remove specific values from one list and the corresponding values in another list 从另一个词典列表中减去词典列表中的值 - Subtract values from list of dictionaries from another list of dictionaries 从第一个列表中获取相应的值并添加到python中的另一个列表中 - take corresponding values from first list and add to another list in python 从一个列表到另一个列表 - List values from one to another list 如何减去列表中的值 - How to subtract values in a list 如何从同一列表中的值减去列表中的值? - How to subtract values from a list with values from the same list? 从一个大列表内的多个词典中提取(间隔)值,并将它们与另一大列表内的对应列表组合 - Extracting (interval) values from multiple dictionaries inside one large list, and combining these with corresponding lists inside another large list Python:将一个列表中的值与另一个列表中的值序列进行匹配 - Python: matching values from one list to the sequence of values in another list Python:将一个列表中的值匹配到另一个列表中的值序列 - Python: matching values from one list to the sequences of values in another list Pandas - lambda - 列表中的值和来自另一列的对应值,其中列表中的值 - Pandas - lambda - values in list and corresponding value from another column where values in list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM