python - 汇总表 : Skip first even number

标签 python

我正在尝试对列表求和,但跳过第一个偶数,然后继续添加列表的其余部分,包括其余的偶数,但我似乎不太正确。

list = [-3, -7, -1, 0, 1, 2, 3, 4, 5, 6, 7] 
def sum_num(num_list):
    sum = 0
    for i in num_list:
        if i % 2 == 0:
            continue
        sum += i
    return sum 
print sum_num(list)

我要么不对所有偶数求和,要么对所有偶数求和。我该怎么做才能跳过第一个偶数? 谢谢!

最佳答案

将您的 if 语句更改为仅成功一次。

def sum_num(num_list):
    total = 0
    once = False
    for i in num_list:
        if i % 2 == 0 and not once:
            once = True
            continue
        total += i
    return total

在它跳过第一个 even 之后,您的 bool once 将为 True,导致 if 条件在连续的 even 中失败。

关于python - 汇总表 : Skip first even number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28225828/

相关文章:

python - 改进我的 python 函数解析 Wordpress/config.php 的建议

python - pygame - 杀死组中的 Sprite 的问题

python - matplotlib animation.save to gif 动画很慢

python - Django Auth,登录问题

python - 在 Ubuntu 14 中安装 QGIS

python - 将包含混合字体的Word文档转换为Unicode

Python:从导入的 css 文件中查找宽度

python - Pandas 根据另一列条件下的值的随机样本替换 NaN 值

python - 如何使用 xlwings 调整宽度列

javascript - 在 HTML 按钮上单击运行 python 文件 (Django)