Skip to main content
 首页 » 编程设计

python之在 Python 字典中的字符串中添加重复出现的字母的字符索引

2025年05月04日24Free-Thinker

例子 对于“苹果”这个词:

['a', 'p', 'p', 'l', 'e'] 
{'a': [[0], False], 'p': [[1], False], 'l': [[3], False], 'e': [[4], False]} 

我不知道如何添加单词中重复出现的字母的索引,使其看起来像:

{'a': [[0], False], 'p': [[1, 2], False], 'l': [[3], False], 'e': [[4], False]} 

到目前为止我得到的代码是:

def creer_dict_mot(): 
    letter_list = obtenir_lettres_mot() 
    mot_choisi = "apple" 
    letter_dict = {} 
    for let in mot_choisi: 
        letter_dict[let] = [[mot_choisi.index(let)], False] 
    return letter_dict 

请您参考如下方法:

两个主要问题;

首先:让我们看一下这个循环:

for let in mot_choisi: 
    letter_dict[let] = [[mot_choisi.index(let)], False] 

在这里,随着循环的每次迭代,您将覆盖该字母的 letter_dict 条目。你不想这样做,因为你最终会得到类似 {'a': [[0], False], 'p': [[2], False], 'l': [ [3], 假], 'e': [[4], 假]} ,这仍然不是你想要的。

相反,您希望能够更新字典中的条目,而不是覆盖它。我们可以通过在进行分配之前检查我们是否已经有一个条目来做到这一点。

for let in mot_choisi: 
    if not let in letter_dict: 
        letter_dict[let] = [[mot_choisi.index(let)], False] 
    else: 
        # Instead of overwriting the dict, we grab the list from the dict value and update it 
        letter_dict[let][0] += [mot_choisi.index(let)]  

第二: .index 总是返回字符串中某个字符第一次出现的索引。因此,当您调用 'apple'.index('p') 时,它将始终返回 1。观察:

my_string = 'apple' 
for let in my_string: 
    idx = my_string.index(let) 
    print(let, idx) 
>>> ('a', 0) 
>>> ('p', 1) 
>>> ('p', 1) # The first occurrence is index 1 
>>> ('l', 3) 
>>> ('e', 4) 

我们如何解决这个问题?我建议调查 enumerate

my_string = 'apple' 
for idx, let in enumerate(my_string): 
    print(let, idx) 
>>> ('a', 0) 
>>> ('p', 1) 
>>> ('p', 2) # Now we see the index we want 
>>> ('l', 3) 
>>> ('e', 4) 

我将把这两个问题的解决方案结合起来作为练习留给读者