您好,登錄后才能下訂單哦!
這期內(nèi)容當中小編將會給大家?guī)碛嘘P(guān)python中怎么消除序列的重復值,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
1、如果僅僅消除重復元素,可以簡單的構(gòu)造一個集合
$ 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中怎么消除序列的重復值了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。