python列表排序代码_将项目插入Python中的排序列表

将项目插入Python中的排序列表

我正在创建一个类,其中的一种方法将新项目插入已排序列表中。 该项目将插入到已排序列表中的更正(已排序)位置。 但是,除[]、[:]、+和len外,我不允许使用任何内置列表函数或方法。 这部分确实让我感到困惑。

最好的方法是什么?

Will S asked 2019-12-25T02:31:01Z

6个解决方案

82 votes

使用bisect模块的分类功能:

>> import bisect

>> a = [1, 2, 4, 5]

>> bisect.insort(a, 3)

>> print(a)

[1, 2, 3, 4, 5]

stanga answered 2019-12-25T02:31:21Z

73 votes

提示1:您可能想研究bisect模块中的Python代码。

提示2:切片可用于列表插入:

>>> s = ['a', 'b', 'd', 'e']

>>> s[2:2] = ['c']

>>> s

['a', 'b', 'c', 'd', 'e']

Raymond Hettinger answered 2019-12-25T02:31:46Z

34 votes

您应该使用bisect模块。 另外,在使用bisect.insort_left之前,需要对列表进行排序

这是一个很大的差异。

>>> l = [0, 2, 4, 5, 9]

>>> bisect.insort_left(l,8)

>>> l

[0, 2, 4, 5, 8, 9]

timeit.timeit("l.append(8); l = sorted(l)",setup="l = [4,2,0,9,5]; import bisect; l = sorted(l)",number=10000)

1.2235019207000732

timeit.timeit("bisect.insort_left(l,8)",setup="l = [4,2,0,9,5]; import bisect; l=sorted(l)",number=10000)

0.041441917419433594

Ricky answered 2019-12-25T02:32:10Z

1 votes

这是您可能的解决方案:

a = [15, 12, 10]

b = sorted(a)

print b # --> b = [10, 12, 15]

c = 13

for i in range(len(b)):

if b[i] > c:

break

d = b[:i] + [c] + b[i:]

print d # --> d = [10, 12, 13, 15]

ngoc thoag answered 2019-12-25T02:32:30Z

0 votes

我现在正在学习算法,所以我想知道等分模块是如何编写的。这是bisect模块中的有关将项目插入已排序列表的代码,该代码使用二分法:

def insort_right(a, x, lo=0, hi=None):

"""Insert item x in list a, and keep it sorted assuming a is sorted.

If x is already in a, insert it to the right of the rightmost x.

Optional args lo (default 0) and hi (default len(a)) bound the

slice of a to be searched.

"""

if lo < 0:

raise ValueError('lo must be non-negative')

if hi is None:

hi = len(a)

while lo < hi:

mid = (lo+hi)//2

if x < a[mid]:

hi = mid

else:

lo = mid+1

a.insert(lo, x)

请叫我小马哥 answered 2019-12-25T02:32:51Z

-5 votes

这是追加列表并将值插入已排序列表的最佳方法:

a = [] num = int(input('How many numbers: ')) for n in range(num):

numbers = int(input('Enter values:'))

a.append(numbers)

b = sorted(a) print(b) c = int(input("enter value:")) for i in

range(len(b)):

if b[i] > c:

index = i

break d = b[:i] + [c] + b[i:] print(d)`

Veera Pathiran answered 2019-12-25T02:33:11Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值