相关文章:Python 列表list中元素去重的6种方式总结
Python 报错TypeError: unhashable type
- 可哈希的元素有:int、float、str、tuple
- 不可哈希的元素有:list、set、dict
1)当 list 中的元素为 int \ float \ str \ tuple 时,可以直接用 set 函数:
a1 = [1, 2, 3, 4, 5, 2, 3, 4] # int
a2 = [1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0] # float
a3 = ['hello', 'hi', 'hello', 'hi'] # str
a4 = [(1, 2), (1, 2)] # tuple
b1 = list(set(a1))
b2 = list(set(a2))
b3 = list(set(a3))
b4 = list(set(a4))
2)当list中的元素为 list \ set \ dict 时,只能调用reduce方法,自己定义一个函数:
from functools import reduce
a = [{"a": 123, "b": 456}, {"a": 123, "b": 456}, {"a": 123, "b": 321}, {"a": 123, "b": 321}]
def list_dict_duplicate_removal(data_list):
run_function = lambda x, y: x if y in x else x + [y]
return reduce(run_function, [[], ] + data_list)
b = list_dict_duplicate_removal(a)