python - Python-为什么我的列表索引超出范围错误?
问题描述
我正在为列表的第 i 个元素设置一个变量,但即使在第一次迭代中我也会出现超出范围的错误。
# code the max() function
def maxinlist(yourlist):
first = 0
second = 0
duplicatelist = yourlist
for i in range(0, len(yourlist) - 1):
first = yourlist[i]
for j in range(len(yourlist) - 1, 0, -1):
second = yourlist[j]
if second > first:
duplicatelist.pop(i)
elif first > second:
duplicatelist.pop(j)
print(duplicatelist[0])
mylist = [1, 4, 8, 2, 5, 100, 44, 2, 5]
maxinlist(mylist)
解决方案
确保在更改主列表时克隆列表duplicatelist
更改以下内容
duplicatelist = yourlist
到
duplicatelist = yourlist[:]
推荐阅读
- vba - 尝试保存时 VBA 宏抛出错误(但仅在一台计算机上)
- angular - 如何在 Angular 中返回 RxJS Observable 的已完成状态
- android - 二进制 XML 文件行:膨胀类时出错
- python - NLTK 中的类似函数总是返回“No Matches”结果
- postgresql - 如何在 Postgres 中对时间段进行逻辑运算?
- wordpress - 带有嵌套中继器的 Wordpress Elementor 自定义小部件
- python - google.cloud 导入存储:无法导入存储
- java - 陷入循环(输入=>异常)java
- excel - 赛车队的 Excel 公式(计算更换日期后的所有驾驶时间)
- jenkins - 条件打印表达式而不是比较时的Jenkins管道