我有兩個串列,我想將第一個串列中的每個數字乘以第二個串列中的所有數字
[1,2]x[1,2,3]
我希望我的結果是這樣的 [(1x1) (1x2) (1x3),(2x1) (2x2) (2x3)]
uj5u.com熱心網友回復:
麻木的
a = np.array([1,2])
b = np.array([1,2,3])
c = (a[:,None]*b).sum(1)
輸出: array([ 6, 12])
Python
a = [1,2]
b = [1,2,3]
c = [sum(x*y for y in b) for x in a]
輸出: [6, 12]
舊答案(每個元素的產品)
麻木的
a = np.array([1,2])
b = np.array([1,2,3])
c = (a[:,None]*b).ravel()
輸出: array([1, 2, 3, 2, 4, 6])
Python
a = [1,2]
b = [1,2,3]
c = [x*y for x in a for y in b]
## OR
from itertools import product
c = [x*y for x,y in product(a,b)]
輸出: [1, 2, 3, 2, 4, 6]
uj5u.com熱心網友回復:
def multiplyLists(list1: list, list2:list) -> list:
toReturn = []
for i in list1:
temp_sum = 0
for j in list2:
temp_sum = i * j
toReturn.append(temp_sum)
return toReturn
uj5u.com熱心網友回復:
另一種使用 numpy 的方法(您可以擴展到兩個串列之間的許多其他功能):
a = [1,2]
b = [1,2,3]
np.multiply.outer(a,b).ravel()
#array([1, 2, 3, 2, 4, 6])
uj5u.com熱心網友回復:
正如評論指出的那樣,純 Python 解決方案與 numpy 解決方案會有很大不同。
派頓
在這里使用嵌套回圈或串列決議會很簡單:
list1 = [1, 2]
list2 = [1, 2, 3]
lst_output = []
for i in list1:
for j in list2:
lst_output .append(i*j)
#equivalent alternative
lst_output = [i*j for i in list1 for j in list2]
麻木
numpy 也有很多方法可以解決這個問題。下面是一個例子:
arr1 = np.array([1, 2])
arr2 = np.array([1, 2, 3])
xx, yy = np.meshgrid(arr1, arr2)
arr_output = xx * yy
# optionally (to get a 1d array)
arr_output_flat = arr_output.flatten()
編輯:再次閱讀您的問題,我注意到您說您實際上希望輸出為 2 個總和(3 個產品)。我建議你更準確地表達你想要的和你嘗試過的。但是要提供以下內容,您可以對上面的串列或陣列執行以下操作:
# Pure Python
lst_output = [sum(i*j for j in list2) for i in list1]
# Numpy
xx, yy = np.meshgrid(arr1, arr2)
arr_output = np.sum(xx * yy, axis=0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/370334.html
上一篇:如何將帶有np.arrays的Pandas系列變成數值?
下一篇:連接numpy陣列后存盤索引
