python去重,一個(gè)由dict組成的list的去重示例
背景:有一個(gè)list,里面的每一個(gè)元素都是dict,根據(jù)某一個(gè)key進(jìn)行去重,在這里,key代表question
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# created by fhqplzj on 2017/12/07 上午11:38
from itertools import groupby
from operator import itemgetter
import pandas as pd
def distinct(items):
questions = map(itemgetter('question'), items)
df = pd.DataFrame({
'items': items,
'questions': questions
})
return df.drop_duplicates(['questions'])['items'].tolist()
def distinct2(items):
exist_questions = set()
result = []
for item in items:
question = item['question']
if question not in exist_questions:
exist_questions.add(question)
result.append(item)
return result
def distinct3(items):
key = itemgetter('question')
items = sorted(items, key=key)
return [next(v) for _, v in groupby(items, key=key)]
def distinct4(items):
from itertools import compress
mask = (~pd.Series(map(itemgetter('question'), items)).duplicated()).tolist()
return list(compress(items, mask))
if __name__ == '__main__':
data = [
{'question': 'a', 'ans': 'b'},
{'question': 'b', 'ans': 'd'},
{'question': 'a', 'ans': 'p'},
{'question': 'b', 'ans': 'e'}
]
print distinct4(data)
以上這篇python去重,一個(gè)由dict組成的list的去重示例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python中Generators教程的實(shí)現(xiàn)
本文主要介紹了Python中Generators教程的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
使用Python創(chuàng)建快捷方式管理應(yīng)用
在Windows系統(tǒng)中,快速訪問常用程序通常通過“開始菜單”中的“應(yīng)用熱門”功能實(shí)現(xiàn),在這篇博客中,我將向你展示如何使用Python和wxPython創(chuàng)建一個(gè)GUI應(yīng)用,幫助用戶輕松將桌面上的快捷方式添加到Windows“開始菜單”的“應(yīng)用熱門”中,需要的朋友可以參考下2024-08-08
簡單實(shí)現(xiàn)python收發(fā)郵件功能
這篇文章主要教大家如何簡單實(shí)現(xiàn)python收發(fā)郵件功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01
從零開始學(xué)Python第八周:詳解網(wǎng)絡(luò)編程基礎(chǔ)(socket)
本篇文章主要介紹了從零開始學(xué)Python第八周:詳解網(wǎng)絡(luò)編程基礎(chǔ)(socket) ,具有一定的參考價(jià)值,有興趣的可以了解一下。2016-12-12
python-tornado的接口用swagger進(jìn)行包裝的實(shí)例
今天小編就為大家分享一篇python-tornado的接口用swagger進(jìn)行包裝的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
python?selenium中Excel數(shù)據(jù)維護(hù)指南
這篇文章主要給大家介紹了關(guān)于python?selenium中Excel數(shù)據(jù)維護(hù)的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-03-03

