每次填充迭代时,python中填充列表的“ for循环”的速度越来越慢

时间:2019-08-06 11:50:48

标签: python list performance loops for-loop

我使用for循环在python中填充了大量列表:

每次迭代时,速度越来越慢。

tdif=[0]*316
for i in tnrange(len(list_ngrams2)):
    store=[]
    for value in list_ngrams2[i]:  
        if  value in features:
            store.append(value)
    tdif[i]=store

列表理解有相同的问题:

tdif=[value for lst in list_ngrams2 for value in lst if value in features]

Run-time analysis

那么如何加快速度呢?

enter image description here

1 个答案:

答案 0 :(得分:0)

表示为列表理解–假设不需要限制或填充tdif中的316个元素:

features_set = set(features)
tdif = [
    [value for value in values if value in features_set]
    for values in list_ngrams2
]