首页 > 解决方案 > 比较包含列表的字典

问题描述

我有一个列表字典,其中包含 26 个键,每个键都有 26 个给定长度的列表。这些键代表英语拉丁字母的字母。该列表包含特定长度的单词在给定位置出现的给定字符。例如,如果我们想表示长度为 5 的单词的出现,我可能会收到以下输出:

D = {'a': [5, 2, 0, 1, 4], ...., 'z': [0, 7, 5, 2, 1]}

我的目标是按索引将键 a 与键 z 进行比较。所以我想将 'a':[5] 与 'z':[0] 进行比较,如果 'a' > 'z' 那么我想返回 a。基本我想比较每个索引,如果该索引较大,我想返回该索引的字母。我目前的代码如下:

def most_common_character_by_index(D):

    for key in D:
        for value in key:
            f = map(D[key], D[value] )
    print(list[f])

想法是映射索引并比较每个索引。也许我错过了什么?当前错误代码返回: print(list[f]) TypeError: 'type' object is not subscriptable

标签: pythonpython-3.xlistdictionary

解决方案


def mostCommonLetters(D):

    numberOfValues = len(D['a'])

    listOfMostCommonLetters = []

    for i in range(numberOfValues):
        currMax = D['a'][i]
        mostCommonLetter = 'a'
        for letter in D:
            if D[letter][i] >= currMax:
                currMax = D[letter][i]
                mostCommonLetter = letter
        listOfMostCommonLetters.append(mostCommonLetter)

    return listOfMostCommonLetters

print(mostCommonLetters({'a': [5, 2, 0, 1, 4],'z': [0, 7, 5, 2, 1]}))

推荐阅读