例
对于“苹果”一词:
['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], False], 'e': [[4], False]}
的内容,这仍然不是您想要的。
相反,您希望能够更新字典中的条目,而不是覆盖它。为此,我们可以在进行分配之前检查是否已经有条目。
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)
我将其留给读者练习,以结合解决这两个问题的方法
关于python - 在Python字典的字符串中添加循环字母的字符索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54727980/