How to use bisect.insort_left with a key?

后端 未结 4 763
时光说笑
时光说笑 2020-12-09 14:34

Doc\'s are lacking an example...How do you use bisect.insort_left)_ based on a key?

Trying to insert based on key.

bisect.insort_left(da         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-09 15:34

    Add comparison methods to your class

    Sometimes this is the least painful way, especially if you already have a class and just want to sort by a key from it:

    #!/usr/bin/env python3
    
    import bisect
    import functools
    
    @functools.total_ordering
    class MyData:
        def __init__(self, color, number):
            self.color = color
            self.number = number
        def __lt__(self, other):
            return self.number < other.number
        def __str__(self):
            return '{} {}'.format(self.color, self.number)
    
    mydatas = [
        MyData('red', 5),
        MyData('blue', 1),
        MyData('yellow', 8),
        MyData('black', 0),
    ]
    mydatas_sorted = []
    for mydata in mydatas:
        bisect.insort(mydatas_sorted, mydata)
    for mydata in mydatas_sorted:
        print(mydata)
    

    Output:

    black 0
    blue 1
    red 5
    yellow 8
    

    See also: "Enabling" comparison for classes

    Tested in Python 3.5.2.

    Upstream requests/patches

    I get the feeling this is going to happen sooner or later ;-)

    • https://github.com/python/cpython/pull/13970
    • https://bugs.python.org/issue4356

提交回复
热议问题