尝试编写自定义排序函数代码时出错

2024-06-28 16:16:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为整数和浮点数创建一个自定义排序函数。在这段代码中,我所做的是先删除重复项,然后尝试使用pop函数从列表中取出最小数字,并将其附加到空列表中,以便每个数字都按正确的顺序排列。然而,当我试图从“列表”中弹出最小数字时,我得到了以下回溯:

line 15, in <module>
    sortedList.append(delDupes.pop(delDupes[test]))
IndexError: pop index out of range

但是如果我用sortedList.append(test)替换上面的那一行,那么我会得到以下错误:

line 14, in <module>
    test = delDupes.index(min(delDupes))
ValueError: min() arg is an empty sequence

下面是代码的外观:

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(delDupes[test]))
    if len(sortedList) != delDupes:
        adLoop = True
    else:
        adLoop = False

print(sortedList)

我使用while循环,这样一旦它弹出最小数量,循环就应该再次启动并弹出下一个最小数量,直到sortedList的长度与增量的原始长度相同


Tags: 函数代码intest列表indexline数字
2条回答

您将收到此错误,因为在此行中

sortedList.append(delDupes.pop(delDupes[test]))

pop期望元素索引,在这里您通过索引test提供delDuples的值

以下是工作代码:

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))

有两个问题:

  1. 正如@Carcigenicate所指出的,它应该是delDupes.pop(test)而不是delDupes.pop(delDupes[test])
  2. 当您从delDupes弹出项目时,它会随着sortedList的增长而变小,因此条件len(sortedList) != delDupes应该是len(delDupes) != 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)

相关问题 更多 >