1
我需要按降序排列第一個元素的列表,然後按升序排列第二個元素。優化函數來排序元組列表
爲此,我實現了以下功能,但我認爲它可能會更快。
>>> 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
+1,你打我。大約在OP的時序測試之間的一半。 – balpha 2010-01-09 19:36:43
+1添加結束符。 – bernie 2010-01-09 19:38:12
謝謝!這對於我來說足夠快:-) >>> timeit.Timer(stmt ='sorted([(int(random.getrandbits(4)),int(random.getrandbits(4)))for xrange( 10)],key = lambda x:( - x [0],x [1]))',setup ='import random;')。timeit(100000) 3.2802747276537048 – jbochi 2010-01-09 19:38:38