This article mainly introduces the method of reversing sequences in Python, and analyzes the specific implementation techniques of list, tuple and string reversal in the form of examples. Friends in need can refer to it. I hope it can help everyone.
Sequence is the most basic data structure in python. Each element in the sequence has a sequence number related to the position, also called an index. For a sequence of N elements,
Index from left to right: 0, 1, 2, ... N-1
Index from right to left: -1, - 2, -3...-N
1》List reversal
>>> 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》Tuple reversal
>>> 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'
The above is the detailed content of Detailed explanation of reverse sequence in Python. For more information, please follow other related articles on the PHP Chinese website!