I'm trying to create a code where the first two numbers of a tuple are multiplied, and then totaled with other tuples. Here's my very wonky code:
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)
Forgot about the output. So basically what is needed is the total of:
total_add = 68.9 + 2, 12.4 + 28, 23.1 + 45, 45.12 + 90
ie the first two numbers of every tuple in the list. Apologies.
If you literally want to add up the product of the first two elements in each tuple, then you can use the sum()
function with a generator:
>>> sum(t[0] * t[1] for t in numbers)
6155.299999999999
which we can check is correct through the following
>>> 68.9 * 2 + 12.4 * 28 + 38.0 * 15 + 23.1 * 45 + 45.12 * 90
6155.299999999999
My preference is to use a vectorised approach via 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
First off, element[1]
will give you the second entry of the tuple, indexing for a tuple or list always starts at 0
. Apart from that, you're giving yourself a hard time with your function by converting variables back and forth. Not sure what you are trying to do with this part anyway:
string_1 = ''.join(str(x) for x in first_decimal)
string_2 = ''.join(str(x) for x in integer)
It seems pretty unecessary. Now to give you a solution that is similar to your approach. Basically, we enumerate through every tuple of the list, multiply the first two entries and add them to the total amound:
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)
or simply:
def function(numbers_list):
total_add = 0
for tuple in numbers_list:
total_add += tuple[0] * tuple[1]
return total_add
which can be further shortened to Joe Iddons answer:
total_add = sum(t[0] * t[1] for t in numbers)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.