逆序排列一个列表

方法1

>>> lst = [1,2,3,4]
>>> lst[::-1]
[4, 3, 2, 1]

方法2

>>> lst = [1,2,3,4]
>>> reversed(lst)
<listreverseiterator object at 0x1006f3e50>
>>> list(reversed(lst))
[4, 3, 2, 1]

方法3

>>> lst = [1,2,3,4]
>>> lst.reverse()
>>> lst
[4, 3, 2, 1]

前两个方法还能运用在string上,一个简单应用就是查找回文词。

>>> lst = ['abcd','efgh','abba','effe']
>>> [w for w in lst if w==w[::-1]]
['abba', 'effe']

results matching ""

    No results matching ""