DeTechn Blog

请写出一段python代码实现删除list里面的重复元素?

l1 = ['b','c','d','c','a','a']
l2 = list(set(l1))
print(l2)

用list类的sort方法:

l1 = ['b','c','d','c','a','a']
l2 = list(set(l1))
l2.sort(key=l1.index)
print(l2)

也可以这样写:

l1 = ['b','c','d','c','a','a']
l2 = sorted(set(l1),key=l1.index)
print(l2)

也可以用遍历:

l1 = ['b','c','d','c','a','a']
l2 = []
for i in l1:
    if not i in l2:
        l2.append(i)
print(l2)

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »