pythontip 映射字符串中的字母

编写一个程序,创建一个字典,其中给定单词的每个唯一字母表示一个键,值为字母出现的索引的列表。

定义函数letter_indices(),参数为word(字符串)。
在函数中,创建一个字典,其中键是单词中的唯一字母,值是包含该字母出现的索引的列表。
返回该字典

version1

点击查看代码
def letter_indices(word):
    dict1={}
    counter=0
    list1=[]
    for i in word:
        dict1[i]=list1.append(int(counter))
        counter+=1
    return dict1

# 获取输入 
word = input()

# 调用函数 
print(letter_indices(word))
* 键能够映射到,但是它的值不能正常映射,原因list.append()他是种添加的方法返回值为None,正确的判断字符是否在字符串内,在就append,else则新建 version2
点击查看代码
def letter_indices(word):
    dict1={}
    list1=[]
    counter=0
    for i in word:
        if i in dict1:
            dict1[i].append(counter)
            counter+=1
        else:
            dict1[i]=[counter]
            counter+=1
    return dict1

# 获取输入 
word = input()

# 调用函数 
print(letter_indices(word))

posted @ 2025-11-11 21:29  硫酸钡barit  阅读(14)  评论(0)    收藏  举报