Python 不打印字符串中唯一单词的多个位置

Python does not print unique word's multiple positions from string

问题是创建一个函数来读取一个字符串并打印一个列出每个 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'))
from collections import defaultdict
s = 'One fish two fish red fish blue fish'
d = defaultdict(list)
for i, word in enumerate(s.split()):
    d[word.lower()].append(i)

使用collections.defaultdict and enumerate. d.items()

dict_items([('one', [0]), ('blue', [6]), ('two', [2]), ('red', [4]), ('fish', [1, 3, 5, 7])])

使用 enumerate() 尝试以下代码:

s = 'One fish two fish red fish blue fish'
res = {}

for i, v in enumerate(s.split(' ')):
    if v in res:
        res[v].append(i)
    else:
        res[v] = [i]

输出:

>>> res
{'blue': [6], 'fish': [1, 3, 5, 7], 'two': [2], 'red': [4], 'One': [0]}

还有另一个答案...

>>> words='One fish two fish red fish blue fish'.split()
>>> counts={}
>>> for word in set(words):
...     counts[word]=[_ for _ in range(len(words)) if words[_]==word]
...     
>>> counts
{'blue': [6], 'two': [2], 'fish': [1, 3, 5, 7], 'red': [4], 'One': [0]}