码迷,mamicode.com
首页 > 其他好文 > 详细

DSU

时间:2014-08-10 18:03:30      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   for   2014   ar   cti   

DSU stands for ‘decorate, sort, undecorate’ and refers to a pattern that is often useful for sorting lists according to some attribute of elements.

For example, if you have a dictionary that maps from mothers to lists of their children, you might want to sort the mothers by their number of children. Here is a function that does that:

bubuko.com,布布扣                       

The first loop assigns each mother to mother and each list of children to children. It builds a list of tuples. Where each tuple is the number of children and a mother. Sort compares the first element, number of children, first, and only considers the second element to break ties. The result of tuples sorted in increasing order by number of children.

The second loop traverses the list of tuples and builds a list of mothers, sorted by parity (which in this context means number of children).

This pattern is called ‘decorate, sort, undecorate’ because the first loop ‘decorates’ the list of mothers by pairing each mother with her parity, and the last loop ‘undecorate’ the sorted list by removing the parity information.

 

from Thinking in Python

DSU,布布扣,bubuko.com

DSU

标签:style   blog   http   io   for   2014   ar   cti   

原文地址:http://www.cnblogs.com/ryansunyu/p/3902886.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!