【发布时间】:2016-12-19 17:29:06
【问题描述】:
问题是创建一个函数来读取一个字符串并打印一个字典,列出每个 UNIQUE 单词的位置。键是单词,值是它在字符串中的位置列表。
这是一个示例字符串:
One fish two fish red fish blue fish
正确的输出是:
{'two': [2], 'one': [0], 'red': [4], 'fish': [1, 3, 5, 7], 'blue': [6]}
这是我的输出:
{'blue': [6], 'two': [2], 'red': [4], 'fish': [1], 'One': [0]}
如您所见,“fish”一词在此字符串中重复了多次。不只是位置1。我需要添加什么代码才能打印出任何单词的多个位置?
这是我的代码:
def wordPositions(s):
d = {}
words = s.split()
for word in words:
lst = []
lst.append(words.index(word))
d[word] = lst
return d
print(wordPositions('One fish two fish red fish blue fish'))
【问题讨论】:
-
...我不认为独特意味着你认为它的意思
-
如果像“fish”这样的词在您的字符串中重复多次,则它不是唯一的。 “one”、“two”、“red”和“blue”是该字符串中的唯一词。
标签: python string python-3.x dictionary position