从python中的列表中删除重复的字符串

时间:2011-11-20 08:30:00

标签: python string

如果我有一个字符串列表,

a = ["asd","def","ase","dfg","asd","def","dfg"]

如何从列表中删除重复项?

4 个答案:

答案 0 :(得分:51)

转换为集合:

a = set(a)

或者可选地返回列表:

a = list(set(a))

请注意,这不会保留顺序。如果您想保留订单:

seen = set()
result = []
for item in a:
    if item not in seen:
        seen.add(item)
        result.append(item)

查看在线工作:ideone

答案 1 :(得分:4)

使用set type删除重复项

a = list(set(a))

答案 2 :(得分:4)

def getUniqueItems(iterable):
result = []
for item in iterable:
    if item not in result:
        result.append(item)
return result

print (''.join(getUniqueItems(list('apple'))))

P.S。同样的事情就像这里的答案之一,但有点变化,设置并不是真的需要!

答案 3 :(得分:3)

您可以将它们弹出到set然后再回到列表中:

a = [ ... ]
s = set(a)
a2 = list(s)
相关问题