我正在学习 python,但我正在做的练习任务遇到了麻烦。该任务希望用户编写一个函数来查看列表并忽略 6 和 9 之间出现的值。但是,对于不在 6 和 9 之间的所有其他项目,它会输出它们的总和。
我尝试使用 for 循环和 while 循环编写程序。但是,我陷入了必须指定项目范围的部分。我知道我应该在 for 循环中使用 while 循环来解决问题。
def addoutside(arrg):
num1 = 0
for num in arrg:
while num != 6:
num1 = num1 + num
while num == 6:
for num2 in range(num):
if.....
addoutside(4,5,6,7,8,9,9)
addoutside(4,5,6,7,8,9,9,10)
addoutside(4,5,6,7,8,9,9,6,5,4,3)
addoutside(1,2,3,6,7,8,9,1,2,3,6,7,9)
编辑:我已经通过提供一些输出的一些示例阐明了我希望该函数如何运行。
Expected output: 18 <---- from the 4+5+9
Expected output: 28 <---- from the 4+5+9+10
Expected output: 36 <---- from the 4+5+9+6+5+4+3
Expected output: 12 <---_ from the 1+2+3+1+2+3
18 应该来自 4 + 5 + 9。该函数应该只忽略 6 和 9 之间出现的字符。从 6 开始,到下一个 9 结束。
最佳答案
我猜这是一个很好的解决方案,它跟踪 sum_after_six 并在看到 9 时从总数中减去它。
但是当它看到新的6时它会重置sum_after_six,我不知道你是否有意这样做?如果没有,您可以添加一个附加条件 if not saw_six and num==6
来重置 sum_after_six
希望这有帮助
arr = [4,5,6,7,8,9,9]
seen_six = False
total = 0
sum_after_six = 0
for num in arr:
total += num
sum_after_six +=num
if num==6:
seen_six = True
sum_after_six = num
elif seen_six and num==9:
total -= sum_after_six
sum_after_six = 0
seen_six = False
print(total)
关于python - 如何告诉 python 忽略列表中两个项目之间的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57368342/