2

これは、Python での文字列インターンに関する以前の質問のフォローアップですが、別の質問として認定するのに十分な関連性はないと思います。要するに、sys.intern を使用する場合、ほとんど/すべての使用時に問題の文字列を関数に渡す必要がありますか、それとも文字列を一度だけインターンしてその参照を追跡する必要がありますか? 私が正しいと思うことを行う疑似コード的なユースケースで明確にするために:(コメントを参照)

# stores all words in sequence, 
# we want duplicate words too,
# but those should refer to the same string
# (the reason we want interning)
word_sequence = []
# simple word count dictionary
word_dictionary = {}
for line in text:
    for word in line: # using magic unspecified parsing/tokenizing logic
        # returns a canonical "reference"
        word_i = sys.intern(word)
        word_sequence.append(word_i)
        try:
            # do not need to intern again for
            # specific use as dictonary key,
            # or is something undesirable done
            # by the dictionary that would require 
            # another call here?
            word_dictionary[word_i] += 1 
        except KeyError:
            word_dictionary[word_i] = 1

# ...somewhere else in a function far away...
# Let's say that we want to use the word sequence list to
# access the dictionary (even the duplicates):
for word in word_sequence:
    # Do NOT need to re-sys.intern() word
    # because it is the same string object
    # interned previously?
    count = word_dictionary[word]
    print(count)

別の辞書の単語にアクセスしたい場合はどうすればよいですか? キーがすでにインターンされている場合でも、key:value を挿入するときに sys.intern() を再度使用する必要がありますか? 説明がありますか?前もって感謝します。

4

1 に答える 1

1

sys.intern() 新しい文字列オブジェクトがあるたびに使用する必要があります。そうしないと、表される値に対して同じオブジェクトがあることを保証できません。

ただし、word_seqリストにはインターンされた文字列オブジェクトへの参照が含まれています。sys.intern()それらを再度使用する必要はありません。ここで文字列のコピーを作成するものはありません(これは不要で無駄です)。

sys.intern()文字列をその値を持つ特定のオブジェクトマップするだけです。その後、戻り値への参照を保持している限り、その 1 つの特定のオブジェクトに引き続きアクセスできることが保証されます。

于 2017-01-01T20:20:33.290 に答える