python - 如何告诉 python 忽略列表中两个项目之间的项目

标签 python

我正在学习 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/

相关文章:

python - 测试所有字典项是否为 'True' 的快速方法

python - 在 Django 中是否有解析提要的工具

python - 回滚后 SQLAlchemy 恢复 "This transaction is inactive"

python - django 用户的用户名和电子邮件相同吗?

python - 使用 elementtree 在 Python 中搜索嵌套 XML

python - 修复 3D 图的锯齿状边缘,选择合适的掩码

python - 计算功能词的频率

python - 文件未找到错误: [Errno 2] No such file or directory: '/tmp/cats-v-dog

python - 无法通过套接字连接到本地 MySQL 服务器 '/tmp/mysql.sock

python - 模块未找到错误 : No module named 'pyspark'