Python中的一个列表的itertools计算只需要显示当前元素

Need to display only the current element of an itertools calculation of a list in Python

创建从元素中减去数字的函数(所有用户输入,并连续计算)时,编译器仅显示所有计算的元素。

尝试将计数器作为参数传递给减法函数,但无论我尝试用 for 循环做什么,我总是收到索引越界错误

def number_list(operator_item): #Creates a list of numbers, after calculation, list is returned to main to be assigned to list_of_numbers variable
    number_list = []
    counter = 1
    print("Enter one value at a time and press enter, press = and enter to proceed")
    while number_list != "=": # Calculations are entered until the user types the equal sign, then the answer is returned to main

        try:
            list_value = float(input())
        except ValueError: # Used an exception to confirm sentinel value, this is to maintain accuracy with float number calculations. No error is handled unless "=" is not entered second time
            sentinel_value = input("Press '=' again to complete calculation and copy answer to system clipboard.\n\n") 
            if sentinel_value == "=":
                copy(running_total)
                return running_total
            else:
                print("Invalid entry!")

        number_list.append(list_value) #Each number that is input will be added to list 
        counter += 1

# I have functions for sum and product, but are excluded for relevance
        if operator_item == "-":
            running_total = subtraction(number_list, counter)
            print("Current difference:", running_total)


def subtraction(number_array, number_element):
    total = list(itertools.accumulate(number_array, operator.sub))
    return total

这是我编译的实际结果。我只是每次减去 5。

一次输入一个值并按回车键,按=并回车继续

5(这是我在键盘上输入的数字)

当前差值:[5.0]

5(这是我在键盘上输入的数字)

当前差值:[5.0, 0.0]

5(这是我在键盘上输入的数字)

当前差值:[5.0, 0.0, -5.0]

我期待它做的是:

一次输入一个值并按回车键,按=并回车继续

5(这是我在键盘上输入的数字)

当前差:5.0

5(这是我在键盘上输入的数字)

当前差:0.0

5(这是我在键盘上输入的数字)

当前差值:-5.0

我怎样才能得到 trim 括号和所有前面的元素?

此行为的原因在于 itertools.accumulate。让我们来看看 docs:

Make an iterator that returns accumulated sums, or accumulated results of other binary functions (specified via the optional func argument).

这是什么意思? accumulate 获取一个可迭代对象和一个函数,并将此函数以特定顺序应用于可迭代对象的元素,return创建一个包含 所有结果的新可迭代对象 .首先它取第一个(两个)元素,然后是那个和第三个元素的结果,那个和第四个元素的结果,依此类推 - 这就是 "accumulating calculation" 所代表的。一个简单的例子:

import itertools

def substraction(array):  # adding number_element as an argument is not needed
    total = list(itertools.accumulate(array, lambda x, y: x-y))
    return total

number_array = [5]
print(substraction(number_array))
# prints [5]  (5=5)

number_array.append(5)  # array is now [5, 5]
print(substraction(number_array))
# prints [5, 0]  (5=5, 5-5=0)

number_array.extend([-5, 4, 6])  # array is now [5, 5, -5, 4, 6]
print(substraction(number_array))
# prints [5, 0, 5, 1, -5]  (5=5, 5-5=0, 0-(-5)=5, 5-4=1, 1-6=-5)

现在,据我了解,您只对该计算的最后一个值感兴趣。有一个名为 functools 的模块具有方便的功能,functools.reduce:

Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value.

所以再一次,它会从左到右累加减去数字,但只是return当前最终结果作为整数,这正是你想要的。

import functools

def substraction(array):
    total = functools.reduce(lambda x, y: x - y, array)  # notice the reversed order of arguments, compared to itertools.accumulate
    return total

number_array = [5]
print(substraction(number_array))
# prints 5 (5=5)

number_array.append(5)
print(substraction(number_array))
# prints 0 ((5)-5=0)

number_array.extend([-5, 4, 6])
print(substraction(number_array))
# prints -5  (((((5)-5)-(-5))-4)-6=-5)

嗯,你的问题出在 substraction 函数中。

问题是你可以保持简单:

from operator import sub
from functools import reduce           # Python 3.x require this.

def substraction(number_list):         # You don't even need the counter param here.
    return reduce(sub, number_list)    # You don't need itertools neither.