【问题标题】:comparing a dictionary containing lists比较包含列表的字典
【发布时间】:2020-03-08 20:07:22
【问题描述】:

我有一个列表字典,其中包含 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' 对象不可下标

【问题讨论】:

  • 也许一个例子可以帮助解释你想说什么
  • 我不太清楚你想做什么。你能举个小例子吗,它不一定是 26 个键,而且列表可能很小,但我根本不清楚你要做什么......“'a' 是什么: [5] 到 'z':[0]" 是什么意思?
  • 提供minimal reproducible example,示例输入和示例输出。
  • @Pitto 那里尝试,但还不是很清楚
  • 在最后一行中将方括号切换为括号将修复您当前的错误。从那里开始工作可能有助于更清楚地说明您要完成的工作。打印(列表(f))

标签: python python-3.x list dictionary


【解决方案1】:
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]}))

【讨论】:

    【解决方案2】:

    主要问题是这样的:

    list[f]
    

    您正在放置括号,这意味着您正在尝试订阅 list 构造函数。因此出现错误。

    你想要的是

    list(f)
    

    反正还有其他问题:

    for value in key: 将遍历密钥本身,您可能需要for value in D[key]

    另外,f 在循环外使用。

    【讨论】:

      猜你喜欢
      • 2012-02-21
      • 1970-01-01
      • 2017-01-03
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 2023-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多