在 Python 中将项目插入排序列表 [英] Insert an item into sorted list in Python
本文介绍了在 Python 中将项目插入排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建一个类,其中的一个方法将一个新项目插入到排序列表中.该项目被插入到排序列表中更正(排序)的位置.我不允许使用除 []
、[:]
、+
和 之外的任何内置列表函数或方法>len
不过.这是让我非常困惑的部分.
I'm creating a class where one of the methods inserts a new item into the sorted list. The item is inserted in the corrected (sorted) position in the sorted list. I'm not allowed to use any built-in list functions or methods other than []
, [:]
, +
, and len
though. This is the part that's really confusing to me.
解决这个问题的最佳方法是什么?
What would be the best way in going about this?
推荐答案
使用 bisect 模块的 rel="noreferrer">insort 函数:
Use the insort function of the bisect module:
import bisect
a = [1, 2, 4, 5]
bisect.insort(a, 3)
print(a)
输出
[1, 2, 3, 4, 5]
这篇关于在 Python 中将项目插入排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文