剑指offer第32题:把数组排成最小的数及关于list.sort()和sorted( Iterable object )函数的相关知识

 * 解题思路:
 * 先将整型数组转 换成字符 数组,然后将String数组排序,最后将排好序的字符串数组拼接出来。关键就是制定 比较规则
 * 排序规则如下:
 * 若ab > ba 则 a > b,
 * 若ab < ba 则 a < b,
 * 若ab = ba 则 a = b;
 * 其中比较规则如下:
自定义 比较规则:比较两个字符串s1, s2大小时,先将它们 拼接起来,比较s1+s2,和s2+s1哪个大,若s1+s2大,则s2应该放前面,反之亦然。 * 比如"3"<"31"但是"331">"313",所以要 将二者拼接起来再进行比较
排序:
可以使用 list.sort()方法来排序,此时 list被修改。也可用 sorted(list),此时 list不变,可将函数返回值赋给另一个变量:newlist= sorted(list)。另一个不同就是 list.sort()方法仅被定义在list中,而sorted()方法对所有的可迭代序列(如字典 等)都有效
python3以前的sorted函数和list.sort()函数都可以加入 cmp参数 ,cmp参数指定一个函数,该函数需要两个参数, 从而实现对list的两两元素进行比较
classSolution:
    def PrintMinNumber(self, numbers):
        # write code here
        ifnot numbers:return""
        numbers = list(map(str,numbers))
        numbers.sort(cmp=lambda  x,y:cmp(x+y,y+x))# cmp参数指定一个函数,该函数需要两个参数
        return'0'ifnumbers[0]=='0'else''.join(numbers)

2)key参数/函数

从python2.4开始, list.sort()和sorted()函数增加了 key参数来指定一个 函数,此 函数 只有一个参数且返回一个值用来进行比较,此函数将在每个元素比较前被调用。这个技术是快速的因为key指定的函数将准确地对每个元素调用。例如:

>>> student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12),('dave', 'B', 10) ]

>>> sorted(student_tuples,  key= l ambda student: student[2]) #  key函数指定一个函数,且该函数只有一个参数
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
同样的技术对拥有命名 属性的复杂对象也适用,例如:
>>> class Student:
def __init__(self, name, grade, age):
    self.name = name
    self.grade = grade
     self.age = age
def __repr__(self):
      return repr((self.name, self.grade, self.age))
>>> student_tuples = [ ('john', 'A', 15), ('jane', 'B', 12),('dave', 'B', 10) ]
>>> sorted(student_tuples, key=lambda student: student.age) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
3)list.sort()和sorted()都接受一个参数reverse(True or False)来表示 升序或降序排序

4)cmp函数:python2.4前,sorted()和list.sort()函数没提供key参数,但提供cmp参数定比较函数。此方法在其他语言中也普遍存在。在python2.x中cmp参数指定的函数需要2个参数,然后返回负数表示小于,0表示等于,正数表示大于,用来进行元素间的比较。例如:

>>> def numeric_compare(x, y):
            return x - y
>>>sorted([5, 2, 4, 1, 3],  cmp=numeric_compare)#cmp参数让用户 指定比较函数,且该函数需要两个参数
[1, 2, 3, 4, 5]
python3.0中,移除了cmp参数 ,若想 将2.x的cmp函数代码移植到3.x,需将cmp函数转化为key函数,即
from functools import  cmp_to_key   #从python2.7, cmp_to_key()函数被增加到了 func tools模块中。
sorted(numbers,key= cmp_to_key(self.comp))
 
# -*- coding:utf-8 -*-
from functools import cmp_to_key
class Solution:
    
    def comp(self,num1,num2):
        t = str(num1)+str(num2)
        s = str(num2)+str(num1)
        if t>s:
            return 1
        elif t<s:
            return -1
        else:
            return 0
    def PrintMinNumber(self,numbers):
        # write code here
        if not numbers: 
            return ""
        numbers = list(map(str, numbers))
        print('numbers:',numbers)
        temnumbers=sorted(numbers,key=cmp_to_key(self.comp))
        print('temnumbers:',temnumbers)
        temnumbers=int(''.join(str(x) for x in temnumbers))
        return temnumbers
        #return int( ''.join(x for x in numbers))
s=Solution()
s1=s.PrintMinNumber([34,3,31])  
print(s1)

猜你喜欢

转载自www.cnblogs.com/wmlj/p/10265803.html