新网创想网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
背景:有一个list,里面的每一个元素都是dict,根据某一个key进行去重,在这里,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)