TypeError: unhashable type: 'list' :python列表去重的小坑

以前在学习的时候,一般对列表去重都是list(set(list))
就是将列表转换成集合在转换成列表,但是在今天的时候却报了一个bug

list_a = [['a', 'b'], ['a', 'b'], ['b', 'c']]
list_a = list(set(list_a))

报的错误为:TypeError: unhashable type: ‘list’
意思就是列表是不可哈希的,去重的方法倒是简单

list_b = list()
for i in list_a:
    if i not in list_b:
        list_b.append(i)

但是在解决完后就要去想它的原因,其实也很简单,集合是无序的非重复的数据聚合到一起,那么肯定是要求里面的数据不可以变化,那么用哈希来判断就是很简单的方法了

发布了119 篇原创文章 · 获赞 14 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_38115310/article/details/103426220