2

文字列リストを指定する関数を探しています。単語と、単語が含まれる行からインデックスを取得します。

s = ['this is the first document',
'this is the second document',
'and this is a third document',
'perhaps there should be a fourth document',
'and now there is a fifth too']

関数を適用すると

def makeInverseIndex(s):

    dic={}
    index=0
    for line in s:
        set=line.split()
        for palabra in set:
            if palabra in dic:
                dic[palabra]=dic[palabra]+[index]
            else:
                dic[palabra]=[index]
        index+=1


    return dic

取得しています

{'a': [2, 3, 4], 'first': [0], 'the': [0, 1], 'and': [2, 4], 'there': [3, 4], 'perhaps': [3], 'document': [0, 1, 2, 3], 'should': [3], 'is': [0, 1, 2, 4], 'be': [3], 'fourth': [3], 'third': [2], 'second': [1], 'too': [4], 'fifth': [4], 'now': [4], 'this': [0, 1, 2]}

しかし、私は取得したいです

{'a': {2, 3, 4}, 'first': {0}, 'the': {0, 1}, 'and': {2, 4}, 'there': {3, 4}, 'perhaps': {3}, 'document': {0, 1, 2, 3}, 'should': {3}, 'is': {0, 1, 2, 4}, 'be': {3}, 'fourth': {3}, 'third': {2}, 'second': {1}, 'too': {4}, 'fifth': {4}, 'now': {4}, 'this': {0, 1, 2}}

コードで何を変更する必要がありますか? リストとセットの違いについて読んだことがあります。セットを使用して {} を取得しようとしていますが、機能していません

皆さん、ありがとうございました

4

1 に答える 1

0

使用dict.setdefault:

def makeInverseIndex(s):
    dic={}
    for index, line in enumerate(s):  #use enumerate() for getting index as well as item
        words = line.split()
        for palabra in words:
            dic.setdefault(palabra,set()).add(index)

set組み込み関数を隠すため、変数名として使用しないでくださいset()

于 2013-07-07T20:45:57.737 に答える