Answers:
这是一个解决方案,只要列表中的值为零,就可以在两个运算符(加减法)之间循环:
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)
尝试这个:
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)
sum
函数!!我认为这就是使用OP sss
而不是使用它的原因sum
lst = [1, 2, 0, 3, 0, 4]
print(sum([v * (-1) ** lst[0:i].count(0) for i, v in enumerate(lst)]))
if i == 0:
可以使用代替if子句sign = not sign
。见repl.it/repls/RigidCrazyDeletions