我有一个多列(13 列)空格分隔的文件(大约 500 万行以上),如下所示:
1. W5 403 407 P Y 2 2 PR 22 PNIYR 22222 12.753 13.247
2. W5 404 408 N V 2 2 PR 22 PIYYR 22222 13.216 13.247
3. W3 274 276 E G 1 1 EG 11 EPG 121 6.492 6.492
4. W3 275 277 P R 2 1 PR 21 PGR 211 6.365 7.503
5. W3 276 278 G Y 1 1 GY 11 GRY 111 5.479 5.479
6. W3 46 49 G L 1 1 GY 11 GRY 111 5.176 5.176
7. W4 47 50 D K 1 1 DK 11 DILK 1111 4.893 5.278
8. W4 48 51 I K 1 1 IK 11 ILKK 1111 4.985 5.552
等等,等等,
我对这些列中的 2 列(第 8 列和第 11 列)感兴趣,并想计算特定对(第 8 列)与后面的字符串(在第 11 列中)的出现次数。
例如,引用键“GY”:“111”的出现次数:2 key 'PR' : # of occurrences of '22222': 2 key 'DK' : # of occurrences of '1111' :1 key 'EG' : # of occurrences of '121': 1
我有一个基于字典的基本实现。
countshash={}
for l in bigtable:
cont = l.split()
if cont[7] not in countshash: countshash[cont[7]] = {}
if cont[11] not in countshash[cont[7]]: countshash[cont[7]][cont[10]] = 0
countshash[cont[7]][cont[10]]+= 1;
我也有一个简单的基于 awk 的计数(速度超快),但我想知道一个 在 python 中执行此操作的高效且快速的方法。感谢您的投入。
最佳答案
我不确定这是否有助于提高速度,但您正在创建大量类似 defaultdict
的对象,我认为您可以使这些对象更具可读性:
from collections import defaultdict
countshash = defaultdict(lambda: defaultdict(int))
for l in bigtable:
cont = l.split()
countshash[cont[7]][cont[10]] += 1
关于python - 计算其中一个引用的三个项目的最快方法(使用 python)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12062830/