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

2024-06-26 14:40:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

['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

Tags: 代码苹果false示例def字母单词dict
3条回答

两个主要问题

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

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

在这里,循环的每次迭代都会覆盖该字母的字母\u 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)

我们怎么解决这个问题?我建议你调查一下^{}

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)

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

另一个简单的选择是在^{}中收集索引,然后在末尾修改它以包含False

from collections import defaultdict

word = 'apple'

d = defaultdict(list)
for idx, letter in enumerate(word):
    d[letter].append(idx)

print({k: [v, False] for k, v in d.items()})
# {'a': [[0], False], 'p': [[1, 2], False], 'l': [[3], False], 'e': [[4], False]}

另外注意字符串是iterable的,因此可以使用'apple'而不是['a', 'p', 'p', 'l', 'e']。你知道吗

试试这个:

def creer_dict_mot():
    s = 'apple'
    d = {}
    for char in s:
        ind = [i for i, a in enumerate(s) if a == char]
        if char not in d:
            d[char] = [ind, False]
    return d

相关问题 更多 >