Home  >  Article  >  Backend Development  >  Detailed explanation of reverse sequence in Python

Detailed explanation of reverse sequence in Python

小云云
小云云Original
2018-03-29 13:44:052359browse

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=&#39;python&#39;
>>> ss=s[::-1]
>>> s
&#39;python&#39;
>>> ss
&#39;nohtyp&#39;
>>> s=&#39;nohtyp&#39;
>>> ss=&#39;&#39;.join(reversed(s))
>>> s
&#39;nohtyp&#39;
>>> ss
&#39;python&#39;

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn