Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 优化函数以对元组列表进行排序_Python_Optimization_Sorting - Fatal编程技术网

Python 优化函数以对元组列表进行排序

Python 优化函数以对元组列表进行排序,python,optimization,sorting,Python,Optimization,Sorting,我需要对元组列表按第一项降序排序,然后按第二项升序排序 为了做到这一点,我实现了以下功能,但我认为它可以更快 >>> compare = lambda a, b: -cmp(b[1], a[1]) if b[0] == a[0] else cmp(b[0], a[0]) >>> sorted([(0, 2), (0, 1), (1, 0), (1, 2)], cmp=compare) [(1, 0), (1, 2), (0, 1), (0, 2)] 有可能优

我需要对元组列表按第一项降序排序,然后按第二项升序排序

为了做到这一点,我实现了以下功能,但我认为它可以更快

>>> compare = lambda a, b: -cmp(b[1], a[1]) if b[0] == a[0] else cmp(b[0], a[0])
>>> sorted([(0, 2), (0, 1), (1, 0), (1, 2)], cmp=compare)
[(1, 0), (1, 2), (0, 1), (0, 2)]
有可能优化它吗?请参阅与内置函数的比较:

>>> timeit.Timer(stmt='sorted([(int(random.getrandbits(4)),int(random.getrandbits(4))) for x in xrange(10)], cmp=compare)', setup='import random; compare=compare = lambda a, b: -cmp(b[1], a[1]) if b[0] == a[0] else cmp(b[0], a[0])').timeit(100000)
4.0584850867917339
>>> timeit.Timer(stmt='sorted([(int(random.getrandbits(4)),int(random.getrandbits(4))) for x in xrange(10)])', setup='import random').timeit(100000)
2.6582965153393161

对我来说,使用键而不是比较函数要快一点,而且可以说更容易阅读:

sorted([(0, 2), (0, 1), (1, 0), (1, 2)], key = lambda x:(-x[0], x[1]))

这需要Python 2.4或更高版本。

对我来说,使用键而不是比较函数要快一点,而且可以说更容易阅读:

sorted([(0, 2), (0, 1), (1, 0), (1, 2)], key = lambda x:(-x[0], x[1]))

这需要Python2.4或更高版本。

这对您有什么好处

compare = lambda a, b: cmp(b[0], a[0]) and cmp(a[1],b[1])

这对你有什么好处

compare = lambda a, b: cmp(b[0], a[0]) and cmp(a[1],b[1])

+你打败了我。在OP的计时测试中间。谢谢!这对我来说已经足够快了:->>>timeit.Timerstmt='sorted[intrandom.getrandbits4,intrandom.getrandbits4 for x in xrange10],key=lambda x:-x[0],x[1]',setup='import random;'。时间100000 3.280274776537048+1,你赢了我。在OP的计时测试中间。谢谢!这对我来说已经足够快了:->>>timeit.Timerstmt='sorted[intrandom.getrandbits4,intrandom.getrandbits4 for x in xrange10],key=lambda x:-x[0],x[1]',setup='import random;'。时间100000 3.280274776537048