python将列表更改为字典



所以我现在正在上python课,我现在正在努力学习字典。我的任务很简单,我需要创建一个函数"letter_position "它将返回一个包含字符串中一个字母的所有位置的字典。

例如

positions = letter_positions("fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's")
positions['e']

应该返回

{4, 5, 8, 14, 16, 43, 67, 83, 88, 89, 97, 121, 122, 141, 142}

所以我几乎完成了分配,但我遇到了一个问题,我有所有的值(位置)分配给键(字母)作为一个列表。

这是我的代码:

def letter_positions(n):
answer = {}
n = n.lower()
x = 0
for letter in n:
if letter.isalpha():
if letter not in answer:
answer[letter] = []
answer[letter].append(x)
x += 1
return answer

所以不是得到一个位置字典而是得到一个位置列表

positions = letter_positions("fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's")
positions['e']

返回

[4, 5, 8, 14, 16, 43, 67, 83, 88, 89, 97, 121, 122, 141, 142]

是否有任何方法可以让我简单地将列表更改为字典,或者我以完全错误的方式接近它?

像这样修改代码

def letter_positions(n):
answer = {}
n = n.lower()
x = 0
for letter in n:
if letter.isalpha():
answer[letter] = answer.get(letter,[])#if there is not the key letter add it as key with value an empty list
answer[letter].append(x)
x=x+1
return answer
positions = letter_positions("fifteen e's, seven f's, four g's, six h's, eight i's, four n's, five o's, six r's, eighteen s's, eight t's, four u's, three v's, two w's, three x's")
print(positions['e'])

相关内容

  • 没有找到相关文章

最新更新