python - 检查列表理解中的总和

标签 python python-3.x

是否也可以用相同的推导方式检查列表中的数字总和,并进行另一个计算,除非总和超过 50?

        k = input("input digits separated by spaces:")
        try:
            [int(i) for i in k.split()]
        except ValueError:
            print("input only digits")

最主要的是不要用两个 except block 来构造它,而是要使其尽可能简单,并确保列表的总和不超过 50。

最佳答案

    k = input("Input integers separated by spaces:")
    try:
        the_list = [int(i) for i in k.split()]
        if sum(the_list) > 50:
            raise ValueError("The user's numbers' summation is too large.")
    except ValueError:
        print("Input only integers separated by spaces with sum not greater than 50.")

关于python - 检查列表理解中的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7282538/

相关文章:

python - 如何在 Windows 10 上同时安装和使用 python 3.8 和 3.7

algorithm - python : List all possible paths in graph represented by dictionary

python - django表单queryset多个相同字段过滤器

Python 和 OpenMP C 扩展

python - 成功进行 SSH key 身份验证后,SSH 和 SCP 命令无法执行,并显示错误消息 : Win32 error 1114

python-3.x - 值错误: DataFrame constructor not properly called when convert Json data to Dataframe

python - 用 Python 制作钻石 ASCII 艺术

python - 如何判断哪个进程正在使用某个文件?

python - 使用 Jinja2 进行简单模板化时设置基本文件路径

python - 在 Python3.6.1 中调用 loop.close asyncio.get_event_loop 后无法创建新的事件循环