直接上例子代码
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14def set_dict(self): print('------start set_dict') result_list = [] dict1 = {'name': 'zhangsan', 'long': 172, 'description': '高的人'} dict2 = {'name': 'lisi', 'long': 172, 'description': '高的人'} dict3 = {'name': 'zhangsan', 'long': 172, 'description': '高的人'} dict4 = {'name': 'zhangsan', 'long': 172, 'description': '高的'} result_list.append(dict1) result_list.append(dict2) result_list.append(dict3) result_list.append(dict4) print(result_list) return result_list
上面这个函数出来的结果是我们本次的测试数据,结果如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17[{ 'name': 'zhangsan', 'long': 172, 'description': '高的人' }, { 'name': 'lisi', 'long': 172, 'description': '高的人' }, { 'name': 'zhangsan', 'long': 172, 'description': '高的人' }, { 'name': 'zhangsan', 'long': 172, 'description': '高的' }]
不难看到结果的list里面有两个dict的结果是一样的,就是172的张三是高的人,我们要想办法去掉这个数据,各种百度之后找到一个比较方便的方法,具体如下:
复制代码
1
2
3
4
5''' 对list格式的dict进行去重''' def remove_list_dict_duplicate(self, list_dict_data): run_function = lambda x, y: x if y in x else x + [y] return reduce(run_function, [[], ] + list_dict_data)
执行后结果如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13[{ 'name': 'zhangsan', 'long': 172, 'description': '高的人' }, { 'name': 'lisi', 'long': 172, 'description': '高的人' }, { 'name': 'zhangsan', 'long': 172, 'description': '高的' }]
已经去掉了重复数据,感觉很实用,记录一下。
最后
以上就是激情小懒猪最近收集整理的关于python中对dict组成的list进行去重的全部内容,更多相关python中对dict组成内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复