Python 对列表list中的int\float\str\tuple\\list\set\dict元素去重

相关文章: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)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值