将项目插入Python中的排序列表 [英] Insert an item into sorted list in Python

查看:77
本文介绍了将项目插入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 ="nofollow noreferrer">分类函数模块:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆