python的list中去掉重复元素

Question Description

网上查询到去掉list中的重复元素的主流方法为使用set()来去重,即

1
2
list_before = [1,2,3,1]
list_after = list(set(list_before))

这样得到的list_after为[1,2,3],但是如果list_before里包括list,比如list_before = [1,2,[3],[3]]还用上述方法的话就会报错:

1
TypeError: unhashable type: 'list'

错误为:list是不能哈希的

Solution

用简单的两个for循环即可解决该问题。

1
2
3
4
5
list_before = [1,2,[3],[3]]
after_before = []
for i in list_before:
if i not in after_before:
after_before.append(i)