python-3.x - 如何在一个单词中找到翻倍?
问题描述
我的任务是检查加倍的单词列表并将结果输出到字典中。
首先我试图执行这段代码:
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'} 等。
解决方案
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 语句;循环将继续并覆盖您找到的结论。我自己实现了你的理由。
推荐阅读
- php - 在 Laravel 7 中构建表单
- node.js - 注册验证 - db.query 中的 if 语句不起作用
- excel - 为什么我的 VBA 代码给我一个“变量未定义”错误?
- php - 使用 POST 参数和递归函数的动态 PHP 网站
- android - 我可以向自定义快餐栏添加边距(扩展 BaseTransientBottomBar)吗?
- flutter - 如何在颤动中创建三次轻击手势?
- sql - 以下 JOIN 问题的有效 SQL 查询是什么
- sql - SQL Server - 选择语句包括变量
- python - OSError 22 无效参数 [将纪元时间戳转换为人类时间]
- selenium - 如何在 anaconda 中安装 selenium 包?