2016-02-05 84 views
1

我写了下面的代码:Python的 - 在字典中的重复值

def word_len_dict(text): 
    the_dict = {} 
    user_input = str(text) 
    words_list = user_input.split() 
    for word in words_list: 
     if len(word) in the_dict: 
      the_dict[len(word)] += [word] 
     else: 
      the_dict[len(word)] = [word] 
    return the_dict 

的文字是:

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

我的输出是走出来的:

2 - ['an', 'he', 'on'] 
3 - ['had', 'had', 'had', 'had', 'his', 'the'] 
4 - ['life', 'that'] 
5 - ['faith'] 
6 - ['affect'] 

我会像我的输出是:

2 - ['an', 'he', 'on'] 
3 - ['had', 'his', 'the'] 
4 - ['life', 'that'] 
5 - ['faith'] 
6 - ['affect'] 

当我将它添加到字典时,我该如何阻止它重复值?

+0

端起来只是让没有 – Nume

回答

2

您可以创建一组出words_list的删除重复

+0

感谢您的重复单词,一个新的列表。结束时只是制作一个没有重复单词的新名单 – Nume

1
for word in words_list: 
    if len(word) in the_dict and word not in the_dict[len(word)]: 
     the_dict[len(word)] += [word] 
    else if len(word) not in the_dict: 
     the_dict[len(word)] = [word] 

或只使用一组

for k,v in the_dict.items(): 
    print k,":",set(v) 

或获得更多的聪明

for word in words_list: 
    if word not in the_dict.get(len(word),[]): 
     the_dict.setdefault(len(word),[]).append(word) 
4
from collections import defaultdict 

def word_len_dict(text): 
    words_by_len = defaultdict(set) 
    for word in text.split(): 
     words_by_len[len(word)].add(word) 
    return words_by_len 

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

{ 
    2: {'an', 'he', 'on'}, 
    3: {'had', 'his', 'the'}, 
    4: {'life', 'that'}, 
    5: {'faith'}, 
    6: {'affect'} 
} 
0

您可以创建一个用户输入中每个单词的单词长度上键入的列表的空字典。这将用一个新的空字典覆盖一些键,但这不会产生任何影响。

接下来,您可以使用列表理解将适当长度的每个单词附加到字典中的相关键(如果它尚不存在)。

text = "the faith that he had had had had an affect on his life" 
words = text.split() 

# Initialize empty list based on word count. 
the_dict = {len(word): [] for word in words} 

# Populate unique words in dictionary. 
[the_dict[len(word)].append(word) for word in words if word not in the_dict[len(word)]] 

>>> the_dict 
{2: ['he', 'an', 'on'], 
3: ['the', 'had', 'his'], 
4: ['that', 'life'], 
5: ['faith'], 
6: ['affect']} 

包裹在一个函数:

def word_len_dict(text): 
    words = text.split() 
    d = {len(word): [] for word in words} 
    [d[len(word)].append(word) for word in words if word not in d[len(word)]] 
    return d 

>>> word_len_dict("the faith that he had had had had an affect on his life") 
{2: ['he', 'an', 'on'], 
3: ['the', 'had', 'his'], 
4: ['that', 'life'], 
5: ['faith'], 
6: ['affect']}