python - sys.intern() 是用于每次查找,还是仅在第一次创建字符串时使用? (Python后续)

标签 python python-3.x dictionary string-interning memory-optimization

这是我之前关于 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)

如果我想访问不同词典中的单词怎么办?插入键:值时是否需要再次使用 sys.intern(),即使该键已被实习? 我可以澄清一下吗?先感谢您。

最佳答案

你必须使用sys.intern() 每次你有一个新的字符串对象,否则你不能保证你有相同的对象的值代表。

但是,您的 word_seq 列表包含对驻留字符串对象的引用。您不必在这些上再次使用 sys.intern()。任何时候都不会在此处创建字符串的副本(即 unnecessary and wasteful )。

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

关于python - sys.intern() 是用于每次查找,还是仅在第一次创建字符串时使用? (Python后续),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41418681/

相关文章:

python - sklearn 树可视化中的这些列表是什么

python - 找到目标后如何停止线程?

Python 脚本无法从 Outlook 获取最新邮件

python-3.x - 应用Python lambda : if condition giving syntax error

ios - 如何在 Swift 中创建混合模式字典

python - 请求 GET 保存不完整的文件

python - 为什么 -ve int 的除法值与 +ve one 不同?

java - Hazelcast ConcurrentMap/MultiMap 键

c++ - 迭代 std::map 的顺序是否已知(并由标准保证)?

python - numpy 1.6.1 未找到多项式对象的求积属性