python消除序列的重复值并保持顺序不变
2017-12-04 18:57
579 查看
python 消除序列的重复值,并保持原来顺序
1、如果仅仅消除重复元素,可以简单的构造一个集合
2、利用集合或者生成器解决:值必须是hashable类型
3、消除元素不可哈希:如字典类型
1、如果仅仅消除重复元素,可以简单的构造一个集合
$ python Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> a = [1 , 3, 5, 1, 8, 1, 5] >>> set(a) {8, 1, 3, 5} >>>
2、利用集合或者生成器解决:值必须是hashable类型
$ python Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> def dupe(items): ... seen = set() ... for item in items: ... if item not in seen: ... yield item ... seen.add(item) ... >>> a = [1 , 3, 5, 1, 8, 1, 5] >>> list(dupe(a)) [1, 3, 5, 8] >>>
3、消除元素不可哈希:如字典类型
Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> def rem(items, key=None): ... seen = set() ... for item in items: ... va = item if key is None else key(item) ... if va not in seen: ... yield item ... seen.add(va 984f ) ... >>> a = [ {'x':1, 'y':2}, {'x':1, 'y':3}, {'x':1, 'y':2}, {'x':2, 'y':4}]>>> list(rem(a, key=lambda d: (d['x'],d['y']))) [{'y': 2, 'x': 1}, {'y': 3, 'x': 1}, {'y': 4, 'x': 2}] >>> list(rem(a, key=lambda d: d['x'])) [{'y': 2, 'x': 1}, {'y': 4, 'x': 2}] >>>>>> #lambda is an anonymous function: ... fuc = lambda : 'haha' >>> print (f()) >>> print (fuc()) haha >>>
相关文章推荐
- Python: 序列list:保持元素顺序同时消除重复值
- Python cookbook(数据结构与算法)从序列中移除重复项且保持元素间顺序不变的方法
- <顺序表>从一个无序顺序表(也可以有序)中删除重复的元素,并使剩余元素间的相对次序保持不变
- 顺序表删除重复元素,并使剩余元素间的相对次序保持不变
- Python中list去重且保持原顺序不变的方法
- 字符串移动(字符串为*号和26个字母的任意组合,把*号都移动到最左侧,把字母移到最右侧并保持相对顺序不变),要求时间和空间复杂度最小
- 【原创】将一个数组中的0元素全部排到数组的右边,其他元素相对顺序保持不变。
- Java中List 去掉重复的值,并保持原先List顺序
- 字符串为*号和26个字母的任意组合把*号都移动到最右侧,把字母移到最右侧并保持相对顺序不变
- Python面试题 之 Uniquify a list 不使用set去除一个列表中的重复项,并且保持原有的排列顺序
- ◆选择重复,消除重复和选择出序列
- Python 单词字母顺序不变且全部倒排
- [python] numpy 三行代码打乱训练数据(保持label和data的对应关系不变)
- Python解决消除重复元素问题【2017年网易春招笔试题】
- ReportingService2008 报表设置中设置报表在滚动时表头保持不变并且在翻页时表头重复显示在每页中
- flag7逆置一句话,但是保持单词顺序不变
- python如何生成重复单一值的序列
- 字符串移动:字符串为*号和26个字母的任意组合把*号都移动到最左侧,把字母移到最右侧并保持相对顺序不变
- 字符串移动(字符串为*号和26个字母的任意组合,把*号都移动到最左侧,把字母移到最右侧并保持相对顺序不变),要求时间和空间复杂度最小 .
- PAT 1093. Count PAT's (25) 求顺序不变的固定子序列数量