小编Mic*_*elA的帖子

for/in/if 列表理解随着大量匹配变得非常缓慢

我的 Python 2.7 代码中有以下列表推导式,它返回行号(索引)和一长串行中的行:

results = [[lines.index(line), line] for line in lines
            if search_item in line.lower()]
Run Code Online (Sandbox Code Playgroud)

如果结果数量很少,这是闪电般的快速:

The search item is: [ 1330 ]
Before string pre-processing, the time is: 0.0000
The number of lines is: 1,028,952
After string pre-processing, the time is: 0.2500
The number of results is: 249
Run Code Online (Sandbox Code Playgroud)

“字符串预处理”就是我所说的结果 = 上面的操作。

这是相同的操作,但使用“1330”作为搜索项而不是“1330”。这个产生 6,049 个匹配而不是 249 个:

The search item is: [1330]
Before string pre-processing, the time is: 0.0000
The number of lines is: 1,028,952
After string pre-processing, the …
Run Code Online (Sandbox Code Playgroud)

python performance list-comprehension list

1
推荐指数
1
解决办法
963
查看次数

标签 统计

list ×1

list-comprehension ×1

performance ×1

python ×1