我正在尝试创建一个代码,其中元组的前两个数字相乘,然后与其他元组进行总计。这是我非常难以理解的代码:
numbers = [(68.9, 2, 24.8),
(12.4, 28, 21.12),
(38.0, 15, 90.86),
(23.1, 45, 15.3),
(45.12, 90, 12.66)]
def function(numbers):
first_decimal = [element[1] for element in numbers]
integer = [element[2] for element in numbers]
string_1 = ''.join(str(x) for x in first_decimal)
string_2 = ''.join(str(x) for x in integer)
# It says 'TypeError: float() argument must be a string or a number',
# but doesn't this convert it to a string??
tot = 1
for element in first_decimal:
tot = float(first_decimal) * int(integer)
return tot
function(numbers)
忘了输出。所以基本上需要的是总数:
total_add = 68.9 + 2, 12.4 + 28, 23.1 + 45, 45.12 + 90
即列表中每个元组的前两个数字。道歉。
如果您真的希望在每个元组中添加前两个元素的乘积,那么您可以将sum()
函数与生成器一起使用:
>>> sum(t[0] * t[1] for t in numbers)
6155.299999999999
我们可以通过以下方式检查是否正确
>>> 68.9 * 2 + 12.4 * 28 + 38.0 * 15 + 23.1 * 45 + 45.12 * 90
6155.299999999999
我的偏好是通过numpy
使用矢量化方法:
import numpy as np
numbers = [(68.9, 2, 24.8),
(12.4, 28, 21.12),
(38.0, 15, 90.86),
(23.1, 45, 15.3),
(45.12, 90, 12.66)]
a = np.array(numbers)
res = np.dot(a[:, 0], a[:, 1])
# 6155.3
首先,element[1]
将为您提供元组的第二个条目,元组或列表的索引始终从0
开始。除此之外,你通过来回转换变量给你自己的功能困难。无论如何,不确定你要对这部分做什么:
string_1 =''。join(first_decimal中x的str(x)) string_2 =''。join(str(x)for x in integer)
这似乎很不必要。现在给你一个类似于你的方法的解决方案。基本上,我们枚举列表的每个元组,将前两个条目相乘并将它们添加到总数中:
numbers = [(68.9, 2, 24.8),
(12.4, 28, 21.12),
(38.0, 15, 90.86),
(23.1, 45, 15.3),
(45.12, 90, 12.66)]
def function(numbers_list):
total_add = 0
# Because numbers is a list of tuples, you can just
# use `len()` to find the number of tuples
for tuple in range(len(numbers_list)):
total_add += numbers_list[tuple][0] * numbers_list[tuple][1]
return total_add
function(numbers)
或者干脆:
def function(numbers_list):
total_add = 0
for tuple in numbers_list:
total_add += tuple[0] * tuple[1]
return total_add
这可以进一步缩短为Joe Iddons回答:
total_add = sum(t[0] * t[1] for t in numbers)