简体   繁体   English

c++排序的python实现

[英]python implementation of c++ sort

    struct node {
        int L, R, i;
    }q[N];

    bool cmp(node x, node y) {
        if(x.L/BLOCK != y.L/BLOCK) {
            // different blocks, so sort by block.
            return x.L/BLOCK < y.L/BLOCK;
        }
        // same block, so sort by R value
        return x.R < y.R;
    }
sort(q, q + m, cmp);

where m is the size of q array.I want to know how to implement the above c++ code in python ie compare on basis of function as third argument.其中 m 是 q 数组的大小。我想知道如何在 python 中实现上述 c++ 代码,即基于函数作为第三个参数进行比较。

You're using a struct q to represent some data.您正在使用 struct q来表示一些数据。 I'm going to assume that you've create an object of the requisite type in python:我将假设您已经在 python 中创建了一个必需类型的对象:

class Q: 
  def __init__(self, L, R, i):
    self.L = L
    self.R = R
    self.i = i

I'm also going to assume that you've defined BLOCK already, and that it's a constant.我还将假设您已经定义了BLOCK ,并且它是一个常量。

So, given you have a list q of objects of type Q , you would sort that list by doing因此,考虑到你有一个列表q类型的对象Q ,你会排序这样做名单

q.sort(lambda x: (x.L/BLOCK, x.R))

that is, calling sort() with a lambda function which returns the 2-tuple for any given element of q .也就是说,使用 lambda 函数调用sort() ,该函数返回q任何给定元素的二元组。 When a sorting key in python returns a tuple, the sort goes in priority order based on that tuple - if xL/BLOCK is equal, only then does it proceed to using xR for comparison.当 python 中的排序键返回一个元组时,排序会根据该元组按优先级顺序进行 - 如果xL/BLOCK相等,则它才会继续使用xR进行比较。

Both list.sort() and the built-in function sorted() take an optional argument that is a function/lambda "key". list.sort()和内置函数sorted()采用一个可选参数,即函数/lambda“键”。 This key outputs the criteria on which to sort, for any given element - similar to the third parameter of std::sort in C++, except it uses a key function instead of a comparator.这个键输出任何给定元素的排序标准——类似于 C++ 中std::sort的第三个参数,除了它使用键函数而不是比较器。 In this case, that works just as well, though.不过,在这种情况下,这也同样有效。

As of 3.0, Python no longer supports using cmp functions in its built-in sorting, only a key function that is expected to map the values to comparable keys.从 3.0 开始,Python 不再支持在其内置排序中使用cmp函数,仅支持将值映射到可比较键的key函数。

Previously, you would use:以前,您将使用:

def cmp(x, y):
    if (x > y):
        return 1
    elif (x < y):
        return -1
    else:
        return 0

sorted([1,3,5,2,4,6], cmp=cmp)

If you don't have a key function available, but only a cmp function, Python has an adaptor function in the functools module:如果没有key函数可用,只有cmp函数,Python在functools模块中有一个适配器函数:

from functools import cmp_to_key

def cmp(x, y):
    if (x > y):
        return 1
    elif (x < y):
        return -1
    else:
        return 0

sorted([1,3,5,2,4,6], key=cmp_to_key(cmp)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM