我的任务是检查加倍单词列表,并将结果输出到字典中。
首先,我试图执行以下代码:
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:“这个词不会加倍”},{anna:“这个病房会加倍”}等等。
答案 0 :(得分:0)
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语句;循环将继续并覆盖您找到的结论。 我对您的原因做了自己的实现。
答案 1 :(得分:0)
wordsList = ["creativity", "anna", "civic", "apology", "refer", "mistress", "rotor", "mindset"]
dictionaries = []
for word in wordsList: #for example:creativity
alphabets=[]
for x in word:
alphabets+=x #now alphabets==['c','r','e','a','t','i','v','i','t','y']
num=0
while True:
x=alphabets[0] #for example 'c'
alphabets.remove(x) #now alphabets==['r','e','a','t','i','v','i','t','y']
if x in alphabets: # if alphabets contain 'c'
doubling=True # it is doubling
break
else:
doubling=False #continue checking
if len(alphabets)==1: #if there is only one left
break #there is no doubling
if doubling:
dictionaries.append({word:"This word has a doubling"})
else:
dictionaries.append({word:"This word has no doubling"})
print(dictionaries)