在包含整数和浮点数的元组列表上的数学运算

时间:2019-01-12 11:28:21

标签: python list tuples element

这是我先前的问题的后续内容,其中我忘记了一部分问题。我下面有一个函数,旨在将一个列表中的元素添加到另一个列表中,直到列表只有0为止。该函数按预期工作,并且可能会使用一些优化,但这是我稍后会尝试的方法。

我当前的问题是我必须以某种方式保持该函数的正常运行,但是我需要使用列表中元组中的浮点数来执行此操作,而不是使用列表中的浮点数来计算值。对于某些背景信息,元组中的int是processID(此代码将在多处理项目中运行),第二个值是根据各种函数计算出的简单float。

列表看起来像这样:

example_list = [(12345, -0.561432), (23456, -0.861423)]

这里是用作工作代码的函数,其示例列表仅包含浮点数(不像我需要的元组)。

def cancelOut(deficit_list, trade_1_list, trade_2_list):

    lengths = [len(deficit_list), len(trade_1_list), len(trade_2_list)]
    # List of the lists of positive values
    positive_lists = [trade_1_list, trade_2_list]

    if(len(deficit_list) != 0): # Check deficit_list isn't empty

        total_positive = lengths[1] + lengths[2]
        current_positive = 0

        # Set all indexes to 0 to start
        deficit_list_index = 0
        trade_index = 0
        trade_lists_index = 0

        # While new_deficit_list contains a value different from 0 do the following
        while not all(value == 0 for value in deficit_list):
            # Determine the difference between the current deficit_list value and current positive value of the current list
            value = deficit_list[deficit_list_index] + positive_lists[trade_lists_index][trade_index]
            if(value > 0):
                positive_lists[trade_lists_index][trade_index] = value
                deficit_list[deficit_list_index] = 0
                deficit_list_index += 1
            elif(value == 0):
                deficit_list[deficit_list_index] = 0
                positive_lists[trade_lists_index][trade_index] = 0
                deficit_list_index += 1
                trade_index += 1
                current_positive += 1
            elif(value < 0):
                deficit_list[deficit_list_index] = value
                positive_lists[trade_lists_index][trade_index] = 0
                current_positive += 1
                if(trade_index == (lengths[trade_lists_index + 1] - 1)):
                    trade_index = 0
                    trade_lists_index = 1
                else:
                    trade_index += 1

            if(trade_lists_index == 1 and current_positive == total_positive):
                break

    return [deficit_list, trade_1_list, trade_2_list]

if __name__ == "__main__":
    deficit_list_values = [-0.246497, -0.341068]
    positive_values_1 = [0.022148, 0.212573, 0.100531]
    positive_values_2 = [0.281474]
    lists = cancelOut(deficit_list_values, positive_values_1, positive_values_2)
    for i in range(len(lists)):
        print(lists[i])

我觉得我遇到的问题是元组包含浮点数和整数。

1 个答案:

答案 0 :(得分:0)

使用以下命令(适用于python 3)

list1, list2 = map(list, zip(*list_of_tuples))
相关问题