python3使用reduce函数去掉列表中重复的字典元素

在 Python3 中,reduce() 函数已经被从全局名字空间里移除了,它现在被放置在 functools 模块里,如果想要使用它,则需要通过引入 functools 模块来调用 reduce() 函数

#!/usr/bin/python3
#coding: utf-8
from functools import reduce

list_dict = [{"name":"sulao"},{"nick":"merci"},{"alias":"shevechco"},{"name":"sulao"}]

def redupliction_remove(list_dict):
    run_function = lambda x, y: x if y in x else x + [y]
    return reduce(run_function, [[], ] + list_dict)

print(redupliction_remove(list_dict))

打印

[{'name': 'sulao'}, {'nick': 'merci'}, {'alias': 'shevechco'}]

reduce的工作过程是 :在迭代sequence(tuple ,list ,dictionary, string等可迭代物)的过程中,首先把 前两个元素传给函数参数,函数加工后,然后把得到的结果和第三个元素作为两个参数传给函数参数, 函数加工后得到的结果又和第四个元素作为两个参数传给函数参数,依次类推。 如果传入了 initial 值, 那么首先传的就不是 sequence 的第一个和第二个元素,而是 initial值和 第一个元素。经过这样的累计计算之后合并序列到一个单一返回值

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://sulao.cn/post/683.html

我要评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。