Insert an item into sorted list in Python

前端 未结 7 962
野趣味
野趣味 2020-11-29 01:06

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

7条回答
  •  青春惊慌失措
    2020-11-29 01:28

    Use the insort function of the bisect module:

    import bisect 
    a = [1, 2, 4, 5] 
    bisect.insort(a, 3) 
    print(a)
    

    Output

    [1, 2, 3, 4, 5] 
    

提交回复
热议问题