Insert an item into sorted list in Python

2019-01-08 15:04发布

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?

5条回答
来,给爷笑一个
2楼-- · 2019-01-08 15:15

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] 
查看更多
你好瞎i
3楼-- · 2019-01-08 15:26

Hint 1: You might want to study the Python code in the bisect module.

Hint 2: Slicing can be used for list insertion:

>>> s = ['a', 'b', 'd', 'e']
>>> s[2:2] = ['c']
>>> s
['a', 'b', 'c', 'd', 'e']
查看更多
倾城 Initia
4楼-- · 2019-01-08 15:26

This is the best way to append the list and insert values to sorted list:

 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)`
查看更多
仙女界的扛把子
5楼-- · 2019-01-08 15:31

You should use the bisect module. Also, the list needs to be sorted before using bisect.insort_left

It's a pretty big difference.

>>> 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
查看更多
太酷不给撩
6楼-- · 2019-01-08 15:31

This is a possible solution for you:

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:
        index = i
        break
d = b[:i] + [c] + b[i:]
print d # --> d = [10, 12, 13, 15]
查看更多
登录 后发表回答