2 回答

TA貢獻1818條經驗 獲得超3個贊
您可以使用:
output=[sorted(sublist,reverse=True) for sublist in input]
print(output)
輸出:
[[4, 3, 2], [8, 7, 5], [9, 4, 1]]

TA貢獻1827條經驗 獲得超8個贊
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.html
In [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-06
In [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]: True
In [34]:
添加回答
舉報