Python实现输入整数直接插入有序列表的方法咨询
问题解答
完全可以实现,你可以在每次插入元素时直接定位到正确的顺序位置插入,全程维护有序列表,不需要最后调用sort()方法。
方案1:使用Python标准库bisect实现(推荐)
bisect是Python自带的二分查找工具库,可以快速定位有序列表中的插入位置,实现代码如下:
import bisect n = int(input()) count = 0 myList = [] while count < n: i = int(input()) # 二分查找得到有序列表的插入位置 insert_pos = bisect.bisect_left(myList, i) myList.insert(insert_pos, i) count += 1 print(myList)
该方案插入位置查找的时间复杂度为O(log n),整体执行效率更高,适合中等规模的数据排序场景。
方案2:手动实现插入位置查找(无依赖)
如果不想引入额外模块,也可以手动遍历查找插入位置,实现逻辑更直观,适合小规模数据场景:
n = int(input()) count = 0 myList = [] while count < n: i = int(input()) # 默认插入到列表末尾 insert_pos = len(myList) # 遍历找到第一个比当前元素大的索引位置 for idx in range(len(myList)): if myList[idx] > i: insert_pos = idx break myList.insert(insert_pos, i) count += 1 print(myList)
内容的提问来源于stack exchange,提问作者xb2107
相关产品推荐
相关产品推荐

