首页 > 解决方案 > 为什么会打印出这么多回复?

问题描述

所以这是我的代码。我目前正在学习 Udacity 课程,并为他们的一个测验编写了这段代码。它给了我我正在寻找的答案.. 但也许似乎发生了太多的迭代,我不确定为什么。如果有人可以帮助我将其减少到一次迭代或打印响应,那就太好了。

numList = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 
   86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
   oddNumList = []
   total = 0

for num in numList:
    if num % 2 != 0:
        oddNumList.append(num)
        if len(oddNumList) < 5:
            print("There are more than 5 odd numbers in this list")
        else:
            for ele in range(0, len(oddNumList)):
                total = total + oddNumList[ele]
                print("Sum of all odd numbers is {}!".format(total))
    

标签: pythonpython-3.xlist

解决方案


你的想法不止一个。如果我不得不猜测我会尝试:

numList = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 
   86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
   oddNumList = []
   total = 0

for num in numList:
    if num % 2 != 0:
        oddNumList.append(num)
# output part
if len(oddNumList) < 5:
    print("There are more than 5 odd numbers in this list")
else:
    for ele in range(0, len(oddNumList)):
        total = total + oddNumList[ele]
    print("Sum of all odd numbers is {}!".format(total))

否则每次检查后都会调用输出函数。

还尝试使用 sum 函数计算总数:sum(oddNumList)


推荐阅读