#python #dictionary #indexing #dataset
Вопрос:
Я полный новичок в python, пытаюсь пройти курс python, и я в тупике из-за этой проблемы: я только возвращаюсь
{'python': [2], 'rules': [2]} # (all words should be lowercase)
Вместо всего набора, который должен быть:
{'python': [0, 2],'time': [0, 1],'it': [1],'is': [1],'that': [1],'rules':[2]}
любая помощь будет признательна!
from collections import defaultdict dataset = [ "Python time", "It is that TIME", "python rules" ] index_dictionary = {} def reverse_index(dataset): for index in range(len(dataset)): phrase = dataset[index] words = phrase.lower() wordlist = words.split() for x in wordlist: if x in index_dictionary.keys(): index_dictionary[x].append(index) else: index_dictionary[x] = [index] return (index_dictionary) print(reverse_index(dataset))
Ответ №1:
Ваш код почти работает нормально, у вас просто небольшая ошибка отступа — у вас должен быть вложенный for
цикл, так как вы хотите, чтобы список слов обновлялся для каждого предложения в наборе данных:
def reverse_index(dataset): index_dictionary = {} for index in range(len(dataset)): phrase = dataset[index] words = phrase.lower() wordlist = words.split() for x in wordlist: if x in index_dictionary.keys(): index_dictionary[x].append(index) else: index_dictionary[x] = [index] return (index_dictionary)
Комментарии:
1. Большое вам спасибо!!!