S = [22, 33, 45.6, 21.6, 51.8]
P = 2.45
此处S
是一个数组
我如何将其乘以并得到值?
SP = [53.9, 80.85, 111.72, 52.92, 126.91]
答案 0 :(得分:66)
在NumPy中它非常简单
import numpy as np
P=2.45
S=[22, 33, 45.6, 21.6, 51.8]
SP = P*np.array(S)
我建议您查看NumPy教程,了解NumPy阵列的全部功能:
https://scipy.github.io/old-wiki/pages/Tentative_NumPy_Tutorial
答案 1 :(得分:35)
您可以使用内置的map
功能:
result = map(lambda x: x * P, S)
或list comprehensions有点pythonic:
result = [x * P for x in S]
答案 2 :(得分:19)
如果您使用numpy.multiply
S = [22, 33, 45.6, 21.6, 51.8]
P = 2.45
multiply(S, P)
它为您提供了结果
array([53.9 , 80.85, 111.72, 52.92, 126.91])
答案 3 :(得分:0)
这是使用functional,map
和itertools.repeat
的operator.mul
方法:
import operator
from itertools import repeat
def scalar_multiplication(vector, scalar):
yield from map(operator.mul, vector, repeat(scalar))
用法示例:
>>> v = [1, 2, 3, 4]
>>> c = 3
>>> list(scalar_multiplication(v, c))
[3, 6, 9, 12]