Home >Backend Development >Python Tutorial >How to arrange string array in reverse order in python

How to arrange string array in reverse order in python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-22 17:14:3311639browse

How to arrange string array in reverse order in python

How to sort string arrays in reverse order in python? Here are several methods:

1. Array reverse order:

Reverse order of the original elements Arrange

(1) Slice

>>> arr = [1,2,3,4,3,4]
>>> print (arr[::-1])
[4, 3, 4, 3, 2, 1]

(2)reverse()

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

(3)reversed(arr) #Return a traversable object in reverse order

arr = [1,2,3,4,3,4]
reversed_arr = [] 
for i in reversed(arr):
    reversed_arr.append(i)
print (reversed_arr)
[4, 3, 4, 3, 2, 1]

2. String reverse order:

Related recommendations: "Python Video Tutorial"

(1)Use string interception

param = 'hello'
print (param[::-1])   
olleh

(2)Use reversed() to return the reversed iterable object (string implementation)

param = 'hello'
rev_str = ''
for i in reversed(param):    
    rev_str += i
print (rev_str)     
olleh

(3)Use reversed() to return the reversed iterable object Iterative object (array implementation)

param = 'hello'
rev_arr = []
for i in reversed(param):
    rev_arr.append(i)
print (''.join(rev_arr))
olleh

Another:

Reverse order of elements after sorting:

1. sorted(...) generates a new sorted array

sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

2. arr.sort(...) directly operates arr, the elements in arr Arrange in positive order

Sort within the element

param = 'hello' #Return the sort within the element

rev_str = ''.join(sorted(param)) # sorted(param) returns the array arranged in reverse order ['e', 'h', 'l', 'l', 'o']
print rev_str ---->'ehllo'

The above is the detailed content of How to arrange string array in reverse order 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