python怎么逆序
发布时间:2025-05-09 10:53:23
如何逆序排列python中的字符串数组?以下是几种方法:
1、数组倒序:
原始元素的倒序排列
(1)切片
>>>arr=[1,2,3,4,3 >>>print(arr[::-1]) [4,3,4,3,2
(2)reverse()
>>>arr=[1,2,3,4,3 >>>arr.reverse() >>>print(arr) [4,3,4,3,2
(3)reversed(arr) #返回一个倒序可以遍历对象
arr=[1,2,3,4,3 reversed_arr=[] foriinreversed(arr): reversed_arr.append(i) print(reversed_arr) [4,3,4,3,2
2、字符串倒序:
相关推荐:Python基础教程
(1)用字符串截取
param='hello' print(param[::-1]) olleh
(2)使用reversed()返回倒可迭代对象(字符串实现)
param='hello' rev_str='' foriinreversed(param): rev_str+=i print(rev_str) olleh
(3)利用reversed()返回倒可迭代对象(数组实现)
param='hello' rev_arr=[] foriinreversed(param): rev_arr.append(i) print(''.join(rev_arr)) olleh
另:
元素排序后的倒序排列:
1、sorted(...)生成新的已排列数组
sorted(iterable,cmp=None,key=None,reverse=False)-->newsortedlist
2、arr.sort(...)直接操作arr,arr内元素正序排列
元素内的排序
param='hello'#返回元素中的排序 rev_str=''.join(sorted(param))#sorted(param)返回倒序排列的数组 ['e','h','l','l','o'] printrev_str 'ehllo'
下一篇 python怎么封装dll