关于算法:如何使这个列表反转算法更高效python

How to make this list reversing algo more efficient python

本问题已经有最佳答案,请猛点这里访问。

我试图颠倒各种列表,我觉得我的代码有些多么优雅,有谁能让它更漂亮呢?

1
2
3
4
5
board = [1,2,3,5]
board = [config[len(config)-1-i] for i,house in enumerate(config)]
print board

#expected output [5,3,2,1]


这应该是您想要的:

1
2
In [2]: board[::-1]
Out[2]: [5, 3, 2, 1]

请参见:https://docs.python.org/2/library/functions.html slice

对于生成器,请参见:https://docs.python.org/2/library/itertools.html itertools.islice


用途:

1
2
3
4
5
6
In[45]: board = [1,2,3,5]

In[46]: board.reverse()

In[47]: board
Out[47]: [5, 3, 2, 1]