Python Reverse Sequence Method Instance analysis, python Reverse Sequence instance analysis
This article describes how to reverse a sequence in Python. We will share this with you for your reference. The details are as follows:
A sequence is the most basic data structure in python. Each element in a sequence has a position-related sequence number, also known as an index. For a sequence with N elements,
Left-to-right index: 0, 1, 2 ,...... N-1
From right to left index:-1,-2,-3 ...... -N
1. Reverse list
>>> l=[1,2,3,4]>>> ll=l[::-1]>>> l[1, 2, 3, 4]>>> ll[4, 3, 2, 1]>>> l=[4,5,6,7]>>> ll=reversed(l)>>> l[4, 5, 6, 7]>>> ll<listreverseiterator object at 0x06A07F70>>>> list(ll)[7, 6, 5, 4]
2. Inverted tuples
>>> t=(2,3,4,5)>>> tt=t[::-1]>>> t(2, 3, 4, 5)>>> tt(5, 4, 3, 2)>>> t=(4,5,6,7)>>> tt=reversed(t)>>> t(4, 5, 6, 7)>>> tt<reversed object at 0x06A07E90>>>> tuple(tt)(7, 6, 5, 4)
3. Reverse the string
>>> s='python'>>> ss=s[::-1]>>> s'python'>>> ss'nohtyp'>>> s='nohtyp'>>> ss=''.join(reversed(s))>>> s'nohtyp'>>> ss'python'