input = [[3,2,4],[5,7,8],[9,1,4]]
output = [[4,3,2],[8,7,5],[9,4,1]]
我感谢您的帮助。有没有一种pythonic的方法?我也有 numpy,所以使用 numpy 会很酷。
我已经集思广益,想尝试通过将每个子列表编写为一维列表,然后按降序编写每个子列表,然后重新引入多维列表来做到这一点。你怎么能这样?我非常数学,所以看到一个非常数学的方法会很酷吗?
input = [[3,2,4],[5,7,8],[9,1,4]]
output = [[4,3,2],[8,7,5],[9,4,1]]
我感谢您的帮助。有没有一种pythonic的方法?我也有 numpy,所以使用 numpy 会很酷。
我已经集思广益,想尝试通过将每个子列表编写为一维列表,然后按降序编写每个子列表,然后重新引入多维列表来做到这一点。你怎么能这样?我非常数学,所以看到一个非常数学的方法会很酷吗?
您可以使用:
output=[sorted(sublist,reverse=True) for sublist in input]
print(output)
输出:
[[4, 3, 2], [8, 7, 5], [9, 4, 1]]
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]: