Insert an item into sorted list in Python

前端 未结 7 948
野趣味
野趣味 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

    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
    

提交回复
热议问题