首页 > 解决方案 > 将项目插入到正确索引的列表中

问题描述

目前正在创建一个重新排序函数,该函数将一个列表中的元素插入到一个空列表中,随后的项目根据该元素from_listto_list. 因此,对于 的原始列表from_list = [4, 5, 6, 3, 9, 88, 2],理想的输出将是to_list = [2, 3, 4, 5, 6, 9, 88]。这是我的代码:

def reorder(to_list, from_list):

    for i in range(len(from_list)):
        if not to_list:
            to_list.insert(0, from_list[i])
        elif from_list[i] < to_list[i - 1] and i == 1:
            to_list.insert(0 , from_list[i])
        elif from_list[i] < to_list[i - 1] and i > 1:
            to_list.insert(to_list[i - 2], from_list[i])
        elif from_list[i] >= to_list[i - 1]:
            to_list.append(from_list[i])

    return to_list

我花了很长时间试图正确放置索引,但是元素没有以正确的顺序插入。对于它的列表,[9, 8, 7, 6, 5, 4, 3]但是[9], [8,9]应该在 9 之前插入 7 i = 2,因此我的意图是将它插入到位置 0。但是它被附加到列表的末尾,导致[8, 9, 7].

我知道 Python 中有特定的重新排序函数,并且有更有效的方法来重新排序现有列表,但是为了这个函数,我的目标是一次读取一个项目并将它们附加到最初为空的列表中.

因此,对于 的初始列表[2, 6, 4, 4, 7],插入顺序将变为[2], [2, 6], [2, 4, 6], [2, 4, 4, 6], [2, 4, 4, 6, 7]

标签: pythonpython-3.xlist

解决方案


有一个内置函数可以将一个项目插入到已经排序的列表中的正确位置,并且会有效地执行此操作 - bisect.insort

>>> import bisect
>>> data = [2, 5, 11, 45, 67]
>>> bisect.insort(data, 7)
>>> data
[2, 5, 7, 11, 45, 67]

推荐阅读