【问题标题】:Combining custom comparison with key selection in python 3将自定义比较与python 3中的键选择相结合
【发布时间】:2018-10-10 18:25:55
【问题描述】:

我正在将一堆 python 2.7 代码迁移到 python 3,它在 python 2.7 中具有这样的模式:

sorted(some_list, cmp=custom_compare, key=custom_key_getter)

我能想到的最好的迁移方法如下:

sorted(some_list, 
       key=functools.cmp_to_key(
             lambda x,y: custom_compare(custom_key_getter(x), 
                                        custom_key_getter(y)))

有没有更好的方法?还是符合python 3的更惯用的方式?

【问题讨论】:

    标签: python python-3.x python-2.7 sorting


    【解决方案1】:

    作为权宜之计,我觉得还可以。

    如果您有 custom_comparecustom_key_getter 的多个组合,我会将 lambda 分解为

    def compare_using(custom_compare, custom_key_getter):
       def comparator(x, y):
         return custom_compare(custom_key_getter(x), custom_key_getter(y))
       return comparator
    

    如果您只有几个组合,我可以想象将它们预先计算,例如

    compare_names_special = compare_using(compare_special, itemgetter('name'))
    ...
    customers_by_name = sorted(customers, compare_names_special)
    

    性能不应该受到影响,因为这段代码只是展示了 Python 2 的排序所做的事情。

    从长远来看,我会考虑重写自定义比较函数,这样它们就不需要cmp_to_key 处理;在大多数情况下,它应该是微不足道的。

    【讨论】:

      猜你喜欢
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-23
      • 2015-02-15
      • 2018-04-05
      相关资源
      最近更新 更多