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

时间:2017-02-12 03:33:01

标签: python list

What I'm getting and what I need to get pic

text = "the faith that he had had had had an affect on his life"

dictionary = {}
text = text.split()
for word in text:
    key = len(word)
    if key in dictionary.keys():
        dictionary[key] += [word]
    else:
        dictionary[key] = [word]
return dictionary

对于文中的单词,有重复的单词。 如何在没有重复单词的情况下返回字典?

2 个答案:

答案 0 :(得分:0)

export interface Dropdown {
  id: string; // maybe number?
  description: string;
}

答案 1 :(得分:-3)

您可以使用set()。集基本上是不能具有重复值的列表。因此,您将列表转换为set(它会删除重复的值),并将其转换回list

my_list = list('hello world')

def remove_duplicate(ls):
    return list(set(ls))

print(remove_duplicate(my_list))

问题在于它没有保持列表项目的顺序。 (至少在python 3.4上)。所以,你可以自己动手:

my_list = list('hello world')

def remove_duplicate(ls):
    new = []
    for item in ls:
        if item not in new:
            new.append(item)
    return new

print(remove_duplicate(my_list))