减去列表的每个值 Python

Subtract each value of a list Python

我正在尝试构建一个简单的计算器。我已经使用 sum 函数完成了加法部分。但是,我无法通过减法实现相同的效果。我想从列表中的每个值中减去它之前的值,即,如果列表(用户输入)是 [10,5,3],我希望我的输出是 10-5-3=2。到目前为止,这是我的代码。

def calculate():
    input = raw_input("input: ")
    if "+" in input:
        sum_val = sum(map(float, input.split('+')))
        if sum_val.is_integer():
            print int(sum_val)
        else:
            print sum_val
    elif "-" in input:
        print map(float, input.split('-'))

calculate()

用户输入可以是 10-5-3。

试试这个 -

user_input = [10, 5, 3]

equation = '-'.join(map(str, user_input))

print(equation, '=', eval(equation))

输出-

10-5-3 = 2
l = [10,5,3]    
s = reduce(lambda x, y: x - y, l)

s == 2

用下面的代码替换map(float, input.split('-'))行,

import functools
import operator

l = map(float, input.split('-'))
r = functools.reduce(operator.sub, l)   # 3

你需要这两个功能:

from operator import sub
from functools import reduce
reduce(sub, map(float, input.split('-')))

试试这个

l = [10,5,3]
if len(l) > 1:
   ans = l[0] - sum(l[1:])
else:
   ans = sum(l)
print(ans)

输出:2

其他答案使用标准函数,特别是 functools.reduce

以下对我来说看起来更简单,但它仅使用意图列表:

head, *tail = [10, 5, 3]
r = sum(-x for x in tail, head)
print(r)

听起来你可以使用 Sentinel。哨兵基本上允许您跟踪循环中的任意条件。加法工作正常,因为您的初始总和为 0,您可以继续添加以增加该值。但是对于减法,您需要用列表中第一个出现的整数在索引 0 处初始化一个 sum 变量。

示例:

sum = 0
print_string = ""
sample_list = [10,5,3]
for i in range(len(sample_list)):
    if (i == 0):
        sum = sample_list[i]
    else:
        sum-=sample_list[i]

    if ((i+1) < len(sample_list)):
        print_string = print_string + str(sample_list[i]) + "-"

    # Now is time to finish it up
    print_string = print_string + "=" + str(sum)

    print(print_string)

输出:

10-5-3=2