【问题标题】:Memory efficient way to create a set from a list of lists in Python从 Python 中的列表列表创建集合的高效内存方法
【发布时间】:2021-03-18 15:17:47
【问题描述】:

我有一个列表列表,其中每个内部列表都是一个标记化的文本,因此它的长度是文本中的单词数。

corpus = [['this', 'is', 'text', 'one'], ['this', 'is', 'text', 'two']]

现在,我想创建一个包含语料库中所有唯一标记的集合。对于上面的示例,所需的输出将是:

{'this', 'is', 'text', 'one', 'two}

目前,我有:

all_texts_list = list(chain(*corpus))
vocabulary = set(all_texts_list)

但这似乎是一种内存效率低下的方式。

有没有更有效的方法来获取这个集合?


我找到了this link。但是,他们希望找到唯一列表的集合,而不是列表中的唯一元素集合。

【问题讨论】:

    标签: python-3.x list set


    【解决方案1】:

    您可以使用带有 set update 操作的简单 for 循环。

    vocabulary = set()
    
    for tokens in corpus:
        vocabulary.update(tokens)
    

    输出:

    {'this', 'one', 'text', 'two', 'is'}
    

    【讨论】:

      猜你喜欢
      • 2014-08-15
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      • 2018-01-31
      • 2017-04-12
      相关资源
      最近更新 更多