Your task is to make a function that can take any non-negative integer as a argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.
Examples:
Input: 21445 Output: 54421
Input: 145263 Output: 654321
Input: 1254859723 Output: 9875543221
很傻的解法:
def Descending_Order(num): l=list(str(num)) l.sort() l.reverse() n=int(''.join(l)) return n
很好的解法:
def Descending_Order(num): return int("".join(sorted(str(num), reverse=True)))
【字符串可以直接sorted,所以我为啥当初非要换成列表??!!】
【因为sort()和sorted()这两个函数用法是不同的,哎妈呀!】
sorted() 函数对所有可迭代的对象进行排序操作。
sort 与 sorted 区别:
sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。(并返回新list)
list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。
==================================智障的分割线================================
值得注意的是:
一、字符串转化成list的命令是 list(字符串)
比如:
mmp='1234765' mmp_list=list(mmp) >>>mmp_list=['1','2','3','4','7','6','5']
二、把列表换成字符串的命令是 ''.join(list)
比如:
list=['1','3','2'] str_l=''.join(list) >>>str_l='132'
其中,‘’中间可以加其他连接符,list也可以跟[:]表示范围,如'-'.join(list[0:2]) 就表示用-连接list里前两个元素。!!