使用重复的字符查找字符串中的索引

sun*_*raj -1 python string

我有字符串 a='51545'

我正在找到字符串中每个字符的索引

modchar=[{i:a.index(i)} for i in a ]

#modchar=[{'5': 0}, {'1': 1}, {'5': 0}, {'4': 3}, {'5': 0}]
Run Code Online (Sandbox Code Playgroud)

但我需要得到它

#modchar=[{'5': 0}, {'1': 1}, {'5': 2}, {'4': 3}, {'5': 4}]
Run Code Online (Sandbox Code Playgroud)

我们怎样才能做到这一点?

mgi*_*son 10

在这种情况下,您可能希望enumerate在创建字典时使用字符串:

[{c: i} for i, c in enumerate(a)]
Run Code Online (Sandbox Code Playgroud)

请注意,作为副作用,这发生在与原始解决方案相反的O(n)时间内,即O(n ^ 2)