这期内容当中小编将会给大家带来有关python中怎么消除序列的重复值,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
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) ... >>> 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中怎么消除序列的重复值了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。