Python 尝试编写自定义排序函数代码时出错
我正在尝试为整数和浮点数创建一个自定义排序函数。在这段代码中,我所做的是先删除重复项,然后尝试使用pop函数从列表中取出最小数字,并将其附加到空列表中,以便每个数字都按正确的顺序排列。然而,当我试图从“列表”中弹出最小数字时,我得到了以下回溯:Python 尝试编写自定义排序函数代码时出错,python,python-3.x,list,Python,Python 3.x,List,我正在尝试为整数和浮点数创建一个自定义排序函数。在这段代码中,我所做的是先删除重复项,然后尝试使用pop函数从列表中取出最小数字,并将其附加到空列表中,以便每个数字都按正确的顺序排列。然而,当我试图从“列表”中弹出最小数字时,我得到了以下回溯: line 15, in <module> sortedList.append(delDupes.pop(delDupes[test])) IndexError: pop index out of range 我正在使用while循环
line 15, in <module>
sortedList.append(delDupes.pop(delDupes[test]))
IndexError: pop index out of range
我正在使用while循环,这样一旦它弹出最小数字,循环应该再次启动并弹出下一个最小数字,直到sortedList的长度与deldupe的原始长度相同
sortedList.append(delDupes.pop(delDupes[test]))
pop
expect元素索引,其中您通过索引test
以下是工作代码:
aList = [30, 30, 30, 20, 20, 20, 25, 25, 25, 10, 10, 10, 50, 50, 50]
delDupes = []
sortedList = []
for i in aList:
if i not in delDupes:
delDupes.append(i)
adLoop = True
while adLoop:
if delDupes:
test = delDupes.index(min(delDupes))
else:
break
try:
sortedList.append(delDupes.pop(delDupes.index(delDupes[test])))
except:
x = 10
if len(sortedList) != delDupes:
adLoop = True
else:
adLoop = False
打印(分类列表)
结果是:[10,20,25,30,50]
UPD:正如Ch3steR在评论中提到的,了解如何以更高效、更简单的方式实现这一点对您很有用:
sorted(set(aList))
有两个问题:
deldups.pop(test)
而不是deldups.pop(deldups[test])
deldups
弹出项目时,它会随着sortedList
的增长而变小,因此条件len(sortedList)!=增量
应为len(增量)!=0
aList = [30, 30, 30, 20, 20, 20, 25, 25, 25, 10, 10, 10, 50, 50, 50]
delDupes = []
sortedList = []
for i in aList:
if i not in delDupes:
delDupes.append(i)
adLoop = True
while adLoop:
test = delDupes.index(min(delDupes))
sortedList.append(delDupes.pop(test))
if len(delDupes) != 0:
adLoop = True
else:
adLoop = False
print(sortedList)
跟踪的错误是什么?我把pop索引弄到了范围之外。你应该一步一步地看一下你的变量值。看来你只是在猜测。您不能使用
delDupes.pop(delDupes[test])
。您将尝试弹出不存在的索引10
。您需要类似于deldups.pop(test)
的东西,因为test
是索引。然后您还需要防止数据重复
为空。可能是而adLoop和DELPES:
?@dante--您真正需要的是而DELPES:
这会导致循环在DELPUS变为空时终止。@dante排序(set(aList))
就足够了。顺便说一句,set是删除重复项的最佳方法。整个代码可以是:sortedList=sorted(set(aList))
。我知道,但问题是“有人能解释一下这里有什么问题吗?”,而不是“我如何最好地解决问题?”sorted(set(aList))
就足够了set
是删除重复项的最佳方法。这是真的,但我猜作者使用此代码是为了学习,他要求帮助代码工作。我还想提到此方法。因此,他知道了一种更有效的方法。
sorted(set(aList))
aList = [30, 30, 30, 20, 20, 20, 25, 25, 25, 10, 10, 10, 50, 50, 50]
delDupes = []
sortedList = []
for i in aList:
if i not in delDupes:
delDupes.append(i)
adLoop = True
while adLoop:
test = delDupes.index(min(delDupes))
sortedList.append(delDupes.pop(test))
if len(delDupes) != 0:
adLoop = True
else:
adLoop = False
print(sortedList)