代码之家  ›  专栏  ›  技术社区  ›  developer_hatch

python,在比较函数中使用两个参数对列表进行排序

  •  7
  • developer_hatch  · 技术社区  · 8 年前

    我看了很多,读了很多问题,但我不知道如何给sort方法的键赋予两个参数,所以我可以进行更复杂的比较。

    例子:

    class FruitBox():
      def __init__(self, weigth, fruit_val):
        self.weigth = weigth
        self.fruit_val = fruit_val
    

    我想比较一下fruit_val的水果盒,但是!而且它们的盒子比其他的大。

    所以它将是:

    f1 = FruitBox(2,5)
    f2 = FruitBox(1,5)
    f3 = FruitBox(2,4)
    f4 = FruitBox(3,4)
    
    boxes = [f1,f2,f3,f4]
    boxes.sort(key = ???) # here is the question
    

    预期结果: => [FruitBox(2,4),FruitBox(3,4),FruitBox(1,5),FruitBox(2,5)]

    当我这样做时,有没有方法发送一个带有2个参数的函数

    def sorted_by(a,b):
      #logic here, I don't know what will be yet
    

    我也这么认为

    boxes.sort(key=sorted_by)
    

    它抛出:

    Traceback (most recent call last):
      File "python", line 15, in <module>
    TypeError: sort_by_b() missing 1 required positional argument: 'b'
    

    我如何给排序键赋予两个参数?

    4 回复  |  直到 8 年前
        1
  •  17
  •   user202729    5 年前

    此答案用于回答:

    我如何给排序键赋予两个参数?


    旧式的比较排序方式在Python 3中已经消失,就像在Python 2中一样:

    def sorted_by(a,b):
        # logic here
        pass
    
    boxes.sort(cmp=sorted_by)
    

    但是如果你必须使用Python 3,它仍然存在,但在一个模块中, functools ,其目的是转换 cmp key :

    import functools 
    cmp = functools.cmp_to_key(sorted_by)
    boxes.sort(key=cmp)
    

    排序的首选方法是生成一个键函数,该函数返回排序所基于的权重。看见 Francisco’s 答复

        2
  •  11
  •   FcoRodr    8 年前

    fruit_val 然后由 weight :

    boxes.sort(key=lambda x: (x.fruit_val, x.weigth))
    
        3
  •  5
  •   randomir    8 年前

    文档,第节 Odd and Ends 说:

    这个 __lt__() 进行比较时 在两个对象之间。因此,通过定义 __lt__() 方法

    __lt__() 给你的 FruitBox 类别:

    class FruitBox():
        def __init__(self, weigth, fruit_val):
            self.weigth = weigth
            self.fruit_val = fruit_val
    
        def __lt__(self, other):
            # your arbitrarily complex comparison here:
            if self.fruit_val == other.fruit_val:
                 return self.weight < other.weight
            else:
                 return self.fruit_val < other.fruit_val
    
            # or, as simple as:
            return (self.fruit_val, self.weight) < (other.fruit_val, other.weight)
    

    然后简单地这样使用:

    sorted(fruitbox_objects)
    
        4
  •  0
  •   Ajax1234    8 年前

    您可以使用 key fruit_val 成员变量:

    boxes = [f1,f2,f3,f4]
    boxes.sort(key=lambda x:x.fruit_val)
    print([i.__dict__ for i in boxes])
    

    输出:

    [{'fruit_val': 4, 'weigth': 2}, {'fruit_val': 4, 'weigth': 3}, {'fruit_val': 5, 'weigth': 2}, {'fruit_val': 5, 'weigth': 1}]
    
    推荐文章