有没有一个函数可以所有两个列表的成对平均值(或总和等)?
我可以编写一个嵌套循环来实现这一点:
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. ]])
但感觉这是一种非常迂回的方式。我想也有嵌套列表理解的选项,但这看起来也很难看。
有没有更好的解决方法呢?
4条答案
按热度按时间tcbh2hod1#
pcww981p2#
您使用的是
numpy
吗?如果是这样的话,您可以广播您的阵列并在一行中获取它。e4eetjau3#
我的感觉是,您可以只使用一个for循环来使事情变得非常干净。通过使用
zip()
函数,可以使代码更简单。O(logn)
时间复杂度最低的最佳方法之一是:ix0qys7i4#
我提出了这样一种清单理解: