我的任务是检查双倍的单词列表并将结果输出到字典中。
首先,我试图执行此代码:
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)
现在它有效,但不是很好。我真的需要建议!提前致谢
我期待输出{创造力:'这个词没有加倍'},{anna:'这个病房加倍'}等。
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)
你忘记了休息声明;循环将继续并覆盖您找到的结论。我自己实现了你的casus。
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)