圆月山庄资源网 Design By www.vgjia.com

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消除序列的重复值并保持顺序不变的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

标签:
python,序列,重复值

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com