首页 > 解决方案 > 如何在一个单词中找到翻倍?

问题描述

我的任务是检查加倍的单词列表并将结果输出到字典中。

首先我试图执行这段代码:

for word in wordsList:
    for letter in word:
        if word[letter] == word[letter+1]:

但只要我有一个错误,我已经改变了一点:

wordsList = ["creativity", "anna", "civic", "apology", "refer", "mistress", "rotor", "mindset"]
dictionary = {}

for word in wordsList:
    for letter in range(len(word)-1):
        if word[letter] == word[letter+1]:
            dictionary[word] = ("This word has a doubling")
        else:
            dictionary[word] = ("This word has no doubling")
print(dictionary)

现在它可以工作,但不能正常工作。我真的需要建议!提前致谢

我期望输出 {creativity: 'This word has no doubleling'}、{anna: 'This ward has a doubleling'} 等。

标签: python-3.x

解决方案


wordsList = ["creativity", "anna", "civic", "apology", "refer", "mistress", "rotor", "mindset"]
dictionary = {}

for word in wordsList:
    for index, char in enumerate(word[:-1]):    # Take one less to prevent out of bounds
        if word[index + 1] == char:             # Check char with next char
            dictionary[word] = True
            break                               # The one you forgot, with the break you wouldnt override the state
    else:
        dictionary[word] = False

print(dictionary)

你忘记了 break 语句;循环将继续并覆盖您找到的结论。我自己实现了你的理由。


推荐阅读