Insert an item into sorted list in Python

前端 未结 7 916
野趣味
野趣味 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] 
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-29 01:31

    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']
    
    0 讨论(0)
  • 2020-11-29 01:36
    # function to insert a number in an sorted list
    
    
    def pstatement(value_returned):
        return print('new sorted list =', value_returned)
    
    
    def insert(input, n):
        print('input list = ', input)
        print('number to insert = ', n)
        print('range to iterate is =', len(input))
    
        first = input[0]
        print('first element =', first)
        last = input[-1]
        print('last element =', last)
    
        if first > n:
            list = [n] + input[:]
            return pstatement(list)
        elif last < n:
            list = input[:] + [n]
            return pstatement(list)
        else:
            for i in range(len(input)):
                if input[i] > n:
                    break
        list = input[:i] + [n] + input[i:]
        return pstatement(list)
    
    # Input values
    listq = [2, 4, 5]
    n = 1
    
    insert(listq, n)
    
    0 讨论(0)
  • 2020-11-29 01:38

    I'm learning Algorithm right now, so i wonder how bisect module writes. Here is the code from bisect module about inserting an item into sorted list, which uses dichotomy:

    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)
    
    0 讨论(0)
  • 2020-11-29 01:39

    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)`
    
    0 讨论(0)
提交回复
热议问题