python中2個串列的所有成對均值(或總和等)是否有函式?
我可以撰寫一個嵌套回圈來執行此操作:
import numpy as np
A = [1,2,3]
B = [8,12,11]
C = np.empty((len(A),len(B)))
for i, x in enumerate(A):
for j, y in enumerate(B):
C[i][j] = np.mean([x,y])
結果:
array([[4.5, 6.5, 6. ],
[5. , 7. , 6.5],
[5.5, 7.5, 7. ]])
但感覺這是一種非常迂回的方法。我想嵌套串列理解也有一個選項,但這看起來也很丑陋。
有沒有更pythonic的解決方案?
uj5u.com熱心網友回復:
你在用numpy嗎?如果是這樣,您可以廣播您的陣列并在一行中實作這一點。
import numpy as np
A = [1,2,3]
B = [8,12,11]
C = (np.reshape(A, (-1, 1)) B) / 2 # Here B will be implicitly converted to a numpy array. Thanks to @Jér?me Richard.
uj5u.com熱心網友回復:
A = [1, 2, 3]
B = [8, 12, 11]
C = np.add.outer(A, B) / 2
# array([[4.5, 6.5, 6. ],
# [5. , 7. , 6.5],
# [5.5, 7.5, 7. ]])
uj5u.com熱心網友回復:
我覺得你可以只使用一個 for 回圈來使事情變得非常干凈。通過使用該zip()功能,您可以使代碼更容易。時間復雜度最低的最佳方法之一O(logn)是:
import numpy as np
A = [1,2,3]
B = [8,12,11]
C = [np.mean([x,y]) for x,y in zip(A,B)] # List Comprehension to decrease lines
print(C)
uj5u.com熱心網友回復:
我建議這樣的串列理解:
C= [[(xx yy)/2 for yy in B] for xx in A]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/525358.html
標籤:Python麻木的
下一篇:根據其他行的值添加行
