直观方法
最简单的思路就是:
1 2 3 4 5 6 7 |
|
相关推荐:《Python基础教程》
使用set方法
1 2 |
|
这样的结果是没有保持原来的顺序。
按照索引再次排序
最后通过这种方式解决:
1 2 3 |
|
使用itertools.grouby方法
如果不考虑列表顺序的话可用这个:
1 2 3 4 5 6 |
|
关于itertools.groupby的原理可以看这里:http://docs.python.org/2/library/itertools.html#itertools.groupby
使用reduce方法
1 2 3 4 |
|
上面是我在ipython中运行的代码,其中的 lambda x,y:x if y in x else x + [y] 等价于 lambda x,y: y in x and x orx+[y] 。
思路其实就是先把ids变为[[], 1,4,3,......],然后在利用reduce的特性。
reduce解释参看这里:http://docs.python.org/2/library/functions.html#reduce