Insert an item into sorted list in Python

前端 未结 7 917
野趣味
野趣味 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:40

    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:
            break
    d = b[:i] + [c] + b[i:]
    print d # --> d = [10, 12, 13, 15]
    
    0 讨论(0)
提交回复
热议问题