是系统实习生()用于每次查找,还是仅在第一次创建字符串时使用?(Python后续)

2024-05-12 21:46:16 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我上一个关于Python中的string interning的问题的后续,尽管我认为它是不相关的,可以作为一个单独的问题。 简而言之,当使用系统实习生,我是否需要在大多数/每次使用时将有问题的字符串传递给函数,还是只需将字符串实习一次并跟踪其引用? 用一个伪代码化的用例来阐明我所做的事情是正确的: (见评论)

# 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)

如果我想从另一本字典中获取单词呢?我需要使用吗系统实习生()当插入键:值,即使钥匙已经被扣留了? 我可以澄清一下吗?提前谢谢你。在


Tags: thetoinforstringdictionary系统count
1条回答
网友
1楼 · 发布于 2024-05-12 21:46:16

每次有一个新的string object时都必须使用sys.intern(),否则无法保证所表示的值具有相同的对象。在

但是,word_seq列表包含对内部字符串对象的引用。你不必再在上面使用sys.intern()。在这里没有任何创建字符串副本的操作(这将是unnecessary and wasteful)。在

sys.intern()所做的就是将字符串值映射到具有该值的特定对象。只要保留对返回值的引用,就可以保证仍然可以访问该特定对象。在

相关问题 更多 >