这里发生的是每个元组的第一个和第二个元素相乘,并且它最终添加了所有产品。我知道如何在Python shell中输入它,但是如何将其作为函数写出来?谢谢你的帮助。
>>> x = [(70.9, 1, 24.8),
(15.4, 2, 70.5),
(30.0, 3, 34.6),
(25.0, 4, 68.4),
(45.00, 5, 99.0)]
>>> result = (a[0]*a[1] for a in x)
>>> sum(result)
>>> 516.7
答案 0 :(得分:4)
创建功能:
def my_func(x):
result = (a[0]*a[1] for a in x)
return sum(result)
调用该函数:
x = [(70.9, 1, 24.8),
(15.4, 2, 70.5),
(30.0, 3, 34.6),
(25.0, 4, 68.4),
(45.00, 5, 99.0)]
my_func(x)
结果将是516.7
答案 1 :(得分:0)
使用numpy packege dot产品我们也可以轻松归档
import numpy as np
x = [(70.9, 1, 24.8),(15.4, 2, 70.5),(30.0, 3, 34.6),(25.0, 4, 68.4),(45.00, 5, 99.0)]
def func(list):
nmpyArray = np.array(list)
mul = np.dot(nmpyArray[:, 0], nmpyArray[:, 1])
print(mul)
return mul
func(x)