我正在尝试编写一个循环,该循环将遍历一个由四个字母组成的单词列表,取单词的最后两个字母,并根据最后两个字符将单词分配给字典键。这就是我目前所掌握的:
dictionary = {}
for z in four_letters: #For each element of the four_letters list
last_letters = getLastLetters(z) #Get the last to letters from the word
if last_letters not in dictionary.keys(): #If the last two letters have not already been made into a key in the dictionary...
dictionary[last_letters] = z #Create a key and add the word as a value
else: #If it has...
dictionary[last_letters].append(z) #Just add the word to the list of values
当我打印字典时,每个键只有一个值,我想知道是否有人能解释我做错了什么,并帮助我纠正它。提前谢谢。
问题就在这一行:
dictionary[last_letters] = z
应该是:
dictionary[last_letters] = [z]
但这里有一个更好的(性能和一些更清洁的(解决方案,你应该考虑。
dictionary = {}
four_letters = [
"dfdf",
"df2f",
"d1df",
"d3df",
"d4df",
"d5df",
"d6df",
"df6f",
"df4f",
]
def getLastLetters(word):
return word[2:]
for word in four_letters: #For each element of the four_letters list
last_letters = getLastLetters(word) #Get the last to letters from the word
try:
dictionary[last_letters].append(word)
except KeyError:
dictionary[last_letters] = [word]
print(dictionary)
样本输出:
{'df': ['dfdf', 'd1df', 'd3df', 'd4df', 'd5df', 'd6df'], '2f': ['df2f'], '6f': ['df6f'], '4f': ['df4f']}
您可以使用dict.setdefault(key, value)
:为每个键设置默认值
def get_last_two_letters(word: str):
return word[len(word) - 2:]
def build_word_dict(four_letters: [str]):
word_dict = {}
for z in four_letters:
last_two_letters = get_last_two_letters(z)
word_dict.setdefault(last_two_letters, []).append(z)
return word_dict
def test_build_word_dict():
four_letters: [str] = ["hell", "bold", "disc", "clap", "ball"]
word_dict = build_word_dict(four_letters)
assert word_dict == {
"ll": [
"hell",
"ball"
],
"ld": [
"bold"
],
"sc": [
"disc"
],
"ap": [
"clap"
]
}