慕仙森
output = [sorted(l)[::-1] for l in input]]与 相比,使用速度最快output = [sorted(l, reverse=True) for l in input]。我也提供了证据。In [4]: input = [[3,2,4],[5,7,8],[9,1,4]] ...: ...: output = [sorted(l)[::-1] for l in input] In [5]: output Out[5]: [[4, 3, 2], [8, 7, 5], [9, 4, 1]]Proof- 哪个最快,sorted(l, reverse=True)或者sorted(l)[::-1]?注意:有关更多详细信息,请timeit访问https://docs.python.org/2/library/timeit.htmlIn [10]: from timeit import timeit In [11]: timeit("[sorted(l)[::-1] for l in [[3,2,4],[5,7,8],[9,1,4]] ]", number=1) Out[11]: 5.978000444883946e-06In [12]: timeit("[sorted(l, reverse=True) for l in [[3,2,4],[5,7,8],[9,1,4]] ]", number=1) Out[12]: 7.292000191227999e-06第一种方法比第二种方法花费的时间更少。In [13]: In [33]: 5.978000444883946e-06 < 7.292000191227999e-06 Out[33]: TrueIn [34]: