如何将此三重for循环转换为列表推导?

问题描述

这是代码。我想将其更改为列表理解,以缩短计算时间。

for sentence in trained['Tweet']:
    for uword in unique:
        for word in sentence.split(' '):
            if uword == word:
                count += 1
        vector[unique.index(uword)] = count
        count = 0
    vlist.append(vector)
    vector = np.zeros(unique_words)

解决方法

最快的方法是使用计数器:

from collections import Counter

sentence_list = ['Hey there dog','there is a dog','it is a good dog']

word_count = Counter(word for sentence in sentence_list for word in sentence.split())

# Output:
# Counter({'dog': 3,'there': 2,'is': 2,'a': 2,'Hey': 1,'it': 1,'good': 1})

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...