【发布时间】:2015-02-09 15:04:30
【问题描述】:
我手头有一个大小合适的文本文件(~ 23MB)。我正在逐行读取文件,并根据一些外部标准从每一行中提取几个单词。为了这个例子,假设每行至少包含六个制表符分隔的值,除了第一个和最后一个之外,我将选择所有值。
我想输出通过这种方式获得的unique单词集,所以很明显我想将提取的单词存储在set中。此外,由于set.update(other) 比循环遍历other 并使用set.add(elem) 一次添加一个单词要快得多,所以我尝试这样做:
all_words = set()
with open(my_tsv_file) as tsv_file:
for line in tsv_file:
wordlist = based_on_some_criteria(line) # this is a list, not a set
all_words.update(wordlist)
这很好用。但是当我将all_words.update(wordlist) 替换为all_words |= wordlist 时,出现以下错误:
TypeError: unsupported operand type(s) for |=: 'set' and 'list'
从文档中,我了解到update 和|= 是等效的。此外,由于|= 应该接受任何可迭代的,我也通过这样做来确认:
import collections
isinstance(wordlist, collections.Iterable) # returns True
为什么使用set.update 的第一种方法有效,而使用|= 的第二种方法无效?
【问题讨论】: