enumerate()
一起來練習 enumerate!給定一個字串,你需要定義函式 retrieve_character_indices(),建立字典 character_indices。字典的每個鍵是字串中獨一無二的字元;對應的值是由該字元在字串中出現位置(索引)所組成的串列。
例如,把字串 'ukulele' 傳入 retrieve_character_indices() 應該得到:{'e': [4, 6], 'k': [1], 'l': [3, 5], 'u': [0, 2]}。
在這個練習中,不能使用任何字串方法!
本練習屬於課程
Python 程式面試題實作練習
練習說明
- 定義一個
for迴圈,同時走訪字串中的字元與其索引。 - 當鍵已存在時,更新字典。
- 當鍵不存在時,更新字典。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
def retrieve_character_indices(string):
character_indices = dict()
# Define the 'for' loop
for index, character in ____(____):
# Update the dictionary if the key already exists
if character in character_indices:
____[____].____(____)
# Update the dictionary if the key is absent
else:
____[____] = [____]
return character_indices
print(retrieve_character_indices('enumerate an Iterable'))