Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:计算单词和过滤单词的最快方法,出现率低_Python_Performance_Filter_Counter - Fatal编程技术网

Python:计算单词和过滤单词的最快方法,出现率低

Python:计算单词和过滤单词的最快方法,出现率低,python,performance,filter,counter,Python,Performance,Filter,Counter,我正试图找到一种非常有效的方法来过滤罕见的单词。对于尺寸为10000 x 28的二维列表,此代码当前需要11秒 你知道我怎样才能提高这项任务的绩效吗 def remove_rare_terms(cluster_word_list): flatten_list = list(itertools.chain.from_iterable(cluster_word_list)) filter_terms = [key for key, val in Counter(flatten_list)

我正试图找到一种非常有效的方法来过滤罕见的单词。对于尺寸为10000 x 28的二维列表,此代码当前需要11秒

你知道我怎样才能提高这项任务的绩效吗

def remove_rare_terms(cluster_word_list):
   flatten_list = list(itertools.chain.from_iterable(cluster_word_list))
   filter_terms = [key for key, val in Counter(flatten_list).items() if val == 1]
   filter_terms_set = set(filter_terms)
   return [[k for k in cluster_word if k not in filter_terms_set] for cluster_word in cluster_word_list]

将列表长度展平为280000。您希望尽可能减少对其进行迭代的时间

在代码中,您已经迭代了大约5次。 1) 建立扁平化列表 2) 生成计数器(展平列表) 3) 构建筛选条件 4) 生成筛选器\u术语\u集 5) 返回语句

从技术上讲,3和4较短,因为它只包含稀有术语。 出于您的目的,您只需要迭代两次。一个在建筑柜台,一个在过滤稀有术语

计数器以迭代器作为输入,您不需要构建列表。计数器(dict)类型的成员资格检查速度接近设置,不需要构建过滤器术语集

def remove_rare_terms(cluster_word_list):

    counter = Counter(itertools.chain.from_iterable(cluster_word_list))
    return [[k for k in cluster_word if counter[k] ==1] for cluster_word in cluster_word_list]

你确定这些数字吗?我创建了随机测试数据并运行了10000行*30个单词*23个字符的函数。它只需要大约150毫秒。您的字符总数是多少?您可以使用
len(“.”join(itertools.chain.from_iterable(cluster\u word\u list))获得该计数。
def remove_rare_terms(cluster_word_list):

    counter = Counter(itertools.chain.from_iterable(cluster_word_list))
    return [[k for k in cluster_word if counter[k] ==1] for cluster_word in cluster_word_list]