python - 在 List Python 中添加负数
问题描述
遵循python代码有什么问题。
List3=[7,5,4,4,3,1,-2,-3,-5,-7]
total=0
i=6
while i>=6:
total = total + List3[i]
i=i+1
if i> len(List3):
break
print(total)
while 循环不应该在 List3[6]=-2 处开始添加并在 i 大于列表长度时中断。我的逻辑有什么问题?它返回:
IndexError Traceback (most recent call last)
<ipython-input-41-7e2f7eca2eb8> in <module>()
4 i=6
5 while 6<= i:
----> 6 totaln = totaln + List3[i]
7 i=i+1
8 if i> len(List3):
IndexError: list index out of range
解决方案
我认为while
循环是错误的。和i = i+1
if 条件应该在while
循环中。第二点i >= len(List3)
是够了。将i > len(List3)
导致最后一个索引超出索引范围
推荐阅读
- ios - Siri Shortcuts 错误案例显示为通知,忽略 NSUserActivity
- c++ - 该 Cpp 代码中是否有任何错误,可能导致不利的输出?
- c++ - C ++如何解决错误:无法转换'const std::__cxx11::basic_string
' 到 'const key_type&' {aka 'const char&'} - angular - 防止 GraphQL 在 NetworkError 上创建 ApolloError
- ios - 前缀:file://,在本地保存文件的路径中
- mysql - 如何在以下条件下选择带有 % 的查询
- python - 在 openshift 上插入 milvus pod 时套接字关闭
- bash - 让 Bash 对测试执行不区分大小写的操作
- r - 在 R 中使用两个 data.frame 进行累积增长
- django - Django 复杂查询