簡體   English   中英

從一個列表中的相應值中減去另一個列表中的值

[英]Subtract values in one list from corresponding values in another list

我有兩個列表:

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

如何從另一個列表中的相應值中減去一個列表中的每個值並創建一個列表,以便:

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

謝謝。

最簡單的方法是使用列表理解

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

map()

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

由於您似乎是一名工程專業的學生,​​因此您可能想要熟悉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]

也許這可能有用。

C = []
for i in range(len(A)):
    difference = A[i] - B[i]
    C.append(difference)

一個班輪:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM