学习资料来自于ring翻译的python cook book.源贴于linuxforum ,此处只是记录我自己的一点理解


行代码完成的QuickSort

很漂亮,但不很实用。

 

def qsort(L):
     if len(L) <= 1: return L
     return qsort([lt for lt in L[1:] if lt < L[0]]) + L[0:1] + \
            qsort([ge for ge in L[1:] if ge >= L[0]])

 

不仅速度上没有标准的列表sort快,最重要的是由于采用了递归调用,当列表大一时就会超出python的递归深度的最大限度。我测试列表长度只能到900多。不过用来展现列表包容的优雅和简练还是相当不错的。

Ps:算法没看懂。 :(




使用sqlorder by 语法来为对象排序

十分有趣的解法。为每组数据逐一将创建sqlSortable对象并放入其中,通过重载__cmp__来重定义cmp比较的结果。

testList =
[sqlSortable(program=program, name=name) for program, name in data]

前面的关键字在替换时{‘program’=program,’name’=name}所以前面的不会被替换掉。

class sqlSortable:
 
     def __init__(self, **args):
         self.__dict__.update(args)
 
     def setSort(self, sortOrder):
         self.sortFields = []
         for text in sortOrder:
             sortBy, direction = (text+' ').split(' ', 1)
             self.sortFields.append((sortBy, direction[0:4].lower(  ) == 'desc'))
 
     def __repr__(self):
         return repr([getattr(self, x) for x, reverse in self.sortFields])
 
     def __cmp__(self, other):
         myFields    = []
         otherFields = []
         for sortBy, reverse in self.sortFields:
             myField, otherField = getattr(self, sortBy), getattr(other, sortBy)
             if reverse:
                 myField, otherField = otherField, myField
             myFields.append(myField)
             otherFields.append(otherField)
         return cmp(myFields, otherFields)
 
 def testSqlSortable(  ):
     data = [('Premier', 'Stealth U-11'), ('Premier', 'Stealth U-10'),
             ('Premier', 'Stealth U-12'),
             ('Co-ed',   'Cyclones'),     ('Co-ed',   'Lightning'),
             ('Co-ed',   'Dolphins'),
             ('Girls',   'Dynamos'),      ('Girls',   'Tigers'),
             ('Girls',   'Dolphins')]
 
     testList = [sqlSortable(program=program, name=name) 
                 for program, name in data]
     
     tests = [['program DESC', 'name'],
              ['name desc', 'program asc']]
 
     for sortBy in tests:
         print '#### Test basic sorting ###', sortBy
         for sortable in testList:
             sortable.setSort(sortBy)
         testList.sort(  )
         for item in testList:
             print item
 
     print '#### Test modification of attributes ###', sortBy
     assert testList[4].name == 'Lightning'
     testList[4].name = 'ZZ 1st name'
     testList.sort(  )
     for item in testList:
         print item
 
 if __name__ == '__main__':
     testSqlSortable(  )

 

 


评论

该日志第一篇评论

发表评论

评论也有版权!