python消除序列的重复值并保持顺序不变的实例
python消除序列的重复值,并保持原来顺序
1、如果仅仅消除重复元素,可以简单的构造一个集合
$python Python3.5.2(default,Nov232017,16:37:01) [GCC5.4.020160609]onlinux Type"help","copyright","credits"or"license"formoreinformation. >>>a=[1,3,5,1,8,1,5] >>>set(a) {8,1,3,5} >>>
2、利用集合或者生成器解决:值必须是hashable类型
$python Python3.5.2(default,Nov232017,16:37:01) [GCC5.4.020160609]onlinux Type"help","copyright","credits"or"license"formoreinformation. >>>defdupe(items): ...seen=set() ...foriteminitems: ...ifitemnotinseen: ...yielditem ...seen.add(item) ... >>>a=[1,3,5,1,8,1,5] >>>list(dupe(a)) [1,3,5,8] >>>
3、消除元素不可哈希:如字典类型
Python3.5.2(default,Nov232017,16:37:01) [GCC5.4.020160609]onlinux Type"help","copyright","credits"or"license"formoreinformation. >>>defrem(items,key=None): ...seen=set() ...foriteminitems: ...va=itemifkeyisNoneelsekey(item) ...ifvanotinseen: ...yielditem ...seen.add(va) ... >>>a=[{'x':1,'y':2},{'x':1,'y':3},{'x':1,'y':2},{'x':2,'y':4}]>>>list(rem(a,key=lambdad:(d['x'],d['y']))) [{'y':2,'x':1},{'y':3,'x':1},{'y':4,'x':2}] >>>list(rem(a,key=lambdad:d['x'])) [{'y':2,'x':1},{'y':4,'x':2}] >>>>>>#lambdaisananonymousfunction: ...fuc=lambda:'haha' >>>print(f()) >>>print(fuc()) haha >>>
以上这篇python消除序列的重复值并保持顺序不变的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。