对列表中的数字求和,但遇到零后更改其符号


9

我需要对列表中的所有数字求和。如果发生0,则开始减法,直到另一个0,开始加法。

例如:

[1, 2, 0, 3, 0, 4] -> 1 + 2 - 3 + 4 = 4
[0, 2, 1, 0, 1, 0, 2] -> -2 - 1 + 1 - 2 = -4
[1, 2] -> 1 + 2 = 3
[4, 0, 2, 3] = 4 - 2 - 3 = -1

这是我尝试过的:

sss = 0

for num in numbers:
    if 0 == num:
        sss = -num
    else:
        sss += num
return sss

Answers:


17

当列表的元素等于0时更改符号。

result = 0
current_sign = 1
for element in your_list:
    if element == 0:
       current_sign *= -1
    result += current_sign*element

2

这是一个解决方案,只要列表中的值为零,就可以在两个运算符(加减法)之间循环:

from operator import add, sub
from itertools import cycle

cycler = cycle([add, sub])
current_operator = next(cycler)

result = 0
my_list = [1, 2, 0, 3, 0, 4]

for number in my_list:
    if number == 0:
        current_op = next(cycler)
    else:
        result = current_operator(result, number)

1

尝试这个:

d = [1, 2, 0, 3, 0, 4]

sum = 0
sign = False
for i in d:
    if i == 0:
        if sign == False:
            sign = True
        else:
            sign = False
    else:
        if sign == False:
            sum += i
        else:
            sum -= i
print(sum)

if i == 0:可以使用代替if子句sign = not sign。见repl.it/repls/RigidCrazyDeletions
戳刺

1
也不要覆盖内置sum函数!!我认为这就是使用OP sss而不是使用它的原因sum
Jab

1

operator模块和按位取反的另一种变化~

import operator

def accum_on_zero(lst):
    res = 0
    ops, pos = (operator.add, operator.sub), 0
    for i in lst:
        if i == 0:
            pos = ~pos
        res = ops[pos](res, i)
    return res


print(accum_on_zero([1, 2, 0, 3, 0, 4]))     # 4
print(accum_on_zero([0, 2, 1, 0, 1, 0, 2]))  # -4 

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.