【问题标题】:python changing a list into a dictionarypython将列表转换为字典
【发布时间】:2022-12-04 03:02:55
【问题描述】:

所以我现在正在上 python 课,目前正在努力学习字典。我的任务很简单,我必须创建一个函数“letter_positions”,它将返回字符串中字母所有位置的字典。

例如

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]

有没有什么办法可以简单地将列表更改为字典,或者我是以完全错误的方式处理这个问题的?

【问题讨论】:

  • 我不太明白你在问什么。 positions 已经是字典,您答案中的列表是与键 e 关联的值。
  • 你能说清楚你的期望是什么吗输出给定输入?

标签: python-3.x list dictionary


【解决方案1】:

如果我正确理解你的问题,你想返回一个带有搜索键(字母)的字典。

以更 Pythonic 的方式实现这一目标的一种方法是使用收藏品 默认指令将索引构建为列表的工厂方法:

from collections import defaultdict

def letter_index(sentence):
    answer = defaultdict(list)
    
    for idx, ch in enumerate(sentence):
        answer[ch].append(idx)
        
    return answer
    
positions = letter_index("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")

ch = 'e'

for k, v in positions.items():
    if k == ch:
        print(k, v)

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

【讨论】:

    猜你喜欢
    • 2015-07-23
    • 1970-01-01
    • 2015-11-14
    • 2016-10-25
    • 2011-11-18
    • 2022-08-16
    • 2019-02-10
    • 1970-01-01
    • 2011-12-08
    相关资源
    最近更新 更多