Python:将元组列表中的数字相乘并合计

时间:2018-03-08 19:18:20

标签: python python-3.x

我正在尝试创建一个代码,其中元组的前两个数字相乘,然后与其他元组进行总计。这是我非常难以理解的代码:

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

即。列表中每个元组的前两个数字。道歉。

3 个答案:

答案 0 :(得分:3)

如果您真的想要在每个元组中添加前两个元素的乘积,那么您可以将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

答案 1 :(得分:1)

我的偏好是通过mean使用矢量化方法:

Yourdf=Yourdf.stack(dropna=False).to_frame().apply(lambda x : (df[x.name[0]]==df[x.name[1]]).mean(),axis=1).unstack()   

答案 2 :(得分:0)

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)