方式一:使用reversed()函数
a=[1,2,3,4,5,6,7,8,9]
b=list(reversed(a))
print(b)
[9, 8, 7, 6, 5, 4, 3, 2, 1]
注意:reversed()函数返回的是一个迭代器,而不是一个List,需要再使用List函数转换一下。
方式二:使用sorted()
a=[1,2,3,4,5,6,7,8,9]
c=sorted(a,key=None, reverse=True)
print(c)
[9, 8, 7, 6, 5, 4, 3, 2, 1]
方式三: 使用分片
a=[1,2,3,4,5,6,7,8,9]
d=a[::-1]
print(d)
[9, 8, 7, 6, 5, 4, 3, 2, 1]
注意:其中[::-1]代表从后向前取值,每次步进值为1
4、汉字按拼音排序
from xpinyin import Pinyin #加载包
def my_function(lis): #输入一个名字的列表
pin=Pinyin()
result=[]
for item in lis:
result.append((pin.get_pinyin(item),item))
result.sort()
for i in range(len(result)):
result[i]=result[i][1]
result=' '.join(result) #将排好序的结果使用空格连接,方便输出
print(result) #输出结果
my_function(['张三','李四','王五','赵六'])
李四 王五 张三 赵六