简化Python词典理解

时间:2020-07-02 08:31:49

标签: python dictionary simplify dictionary-comprehension

我有一个任务,我要创建一个程序,该程序接收一个字符串列表并返回一个字典,该字典将所有输入字符串中的每个单词映射到由该单词出现的所有字符串的字符串编号组成的集合。在实际问题中,字符串是文本的段落,第一个索引为1。

以下是输入->输出示例:

L = ['a b c d e','a b b c c','d e f f']

makeInverseIndex(L)-> {'a':[1,2],'b':[1,2],'c':[1,2],'d':[1,3], 'e':[1,3],'f':[3]}

我有两个可行的解决方案:

import '{path}/globals.dart' as globals

Panel()

// This will give out the updated data if the button is hit else {'a': 0, 'b': 0, 'c': 0}
print(globals.mydata) 

我的问题是,可以使用枚举以任何方式简化dict的理解。教科书中的问题暗示我应该使用枚举,尽管我无法弄清楚如何实现它。

这是我的最佳尝试,尽管我知道由于分配错误这是错误的 即w在列表理解中分配给该对象,但在以下行中未被识别:

def makeInverseIndex(strlist): 
    InvInd = {}
    for i, d in enumerate(strlist):
        for w in d.split():
            if w not in InvInd:
                InvInd[w] = [i+1]
            elif w in d and i+1 not in InvInd[w]:
                InvInd[w].append(i+1)
    return InvInd

def makeInverseIndex2(strlist): return {x:[d+1 for d in range(len(strlist)) if x in strlist[d]]
                                            for w in strlist for x in w.split()}
 for x in w.split()

我感觉很亲密,我确定解决方案可能很明显,但是我无法解决!

谢谢

3 个答案:

答案 0 :(得分:1)

结合枚举使用字典理解

def makeInverseIndex4(strlist):
  return {x:[d+1 for d, v in enumerate(strlist) if x in v] for w in strlist for x in w.split()}

或者我们可以使用start = 1而不是d + 1的枚举

def makeInverseIndex4(strlist):
      return {x:[d for d, v in enumerate(strlist, start=1) if x in v] for w in strlist for x in w.split()}

输出

{'a': [1, 2], 'b': [1, 2], 'c': [1, 2], 'd': [1, 3], 'e': [1, 3], 'f': [3]}

答案 1 :(得分:0)

from collections import defaultdict

L = ["a b c d e", "a b b c c", "d e f f"]
make_inverse_index = defaultdict(set)

for index, line in enumerate(L):
    for word in line.split():
        make_inverse_index[word].add(index + 1)

make_inverse_index = {key: list(value) for key, value in make_inverse_index.items()}

print(make_inverse_index)

输出:

{"a": [1, 2], "b": [1, 2], "c": [1, 2], "d": [1, 3], "e": [1, 3], "f": [3]}

答案 2 :(得分:0)

这对我有用:

def makeInverseIndex3(strlist):
    dict_f = {}
    for i, w in enumerate(strlist):
        for x in set(w.split()):
            dict_f[x] = [i + 1] + dict_f.get(x, [])
    return(dict_f)

输出:

strlist = ['a b c d e', 'a b b c c', 'd e f f']
print(makeInverseIndex3(strlist))

{'e': [3, 1], 'a': [2, 1], 'c': [2, 1], 'd': [3, 1], 'b': [2, 1], 'f': [3]}
相关问题