python - 为什么会打印出这么多回复?
问题描述
所以这是我的代码。我目前正在学习 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))
解决方案
你的想法不止一个。如果我不得不猜测我会尝试:
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)
推荐阅读
- elasticsearch - ElasticSearch - 完全匹配等于操作的单词
- postgresql - 教师 SQL 的课数
- javascript - 吊装说明
- python - Python - 在数据框中查找值并返回随机对应值
- java - 提醒通知未在 android O 及更高版本中显示
- javascript - 将 ImageData 转换为 JS 中的 blob?
- emacs - Emacs - 如何让弹丸在当前窗口中打开文件?
- python - Django -AttributeError:'str'对象没有属性'objects'
- android - Android Studio:不允许操作(绑定失败)
- python - 如何在 Python 中处理包含合并 (colspan = 2) 列的 html 表(最好使用 Beautifulsoup)?