numpy 两个列表的元素之间的所有成对平均值

vawmfj5a  于 2022-11-10  发布在  其他
关注(0)|答案(4)|浏览(104)

有没有一个函数可以所有两个列表的成对平均值(或总和等)?
我可以编写一个嵌套循环来实现这一点:

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

但感觉这是一种非常迂回的方式。我想也有嵌套列表理解的选项,但这看起来也很难看。
有没有更好的解决方法呢?

tcbh2hod

tcbh2hod1#

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. ]])
pcww981p

pcww981p2#

您使用的是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.
e4eetjau

e4eetjau3#

我的感觉是,您可以只使用一个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)
ix0qys7i

ix0qys7i4#

我提出了这样一种清单理解:

C= [[(xx+yy)/2 for yy in B] for xx in A]

相关问题