4

我有一个多列(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 列)感兴趣,并想用后面的字符串(在第 11 列中)计算特定对(第 8 列)的出现次数。

例如,参考键“GY”:“111”的出现次数:2 键“PR”:“22222”的出现次数:2 键“DK”:“1111”的出现次数:1 键“EG” :“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 中一种高效且更快的方法。感谢您的投入。

4

4 回答 4

4
from collections import Counter
Counter(tuple(row.split()[8:12:3]) for row in bigtable)

使用itemgetter更灵活,可能比切片更有效

from operator import itemgetter
ig = itemgetter(8, 11)
Counter(ig(row.split()) for row in bigtable)

使用imap也可以让事情变得更快

from itertools import imap
Counter(imap(ig, imap(str.split, bigtable)))
于 2012-08-21T21:20:55.663 回答
4

我不确定这是否有助于提高速度,但是您正在创建大量defaultdict-like 对象,我认为您可以使它们更具可读性:

from collections import defaultdict

countshash = defaultdict(lambda: defaultdict(int))

for l in bigtable:
    cont = l.split()
    countshash[cont[7]][cont[10]] += 1
于 2012-08-21T21:02:00.250 回答
1
from collections import defaultdict

countshash = defaultdict(int)
for l in bigtable:
    cont = l.split()
    countshash[cont[7], cont[10]] += 1
于 2012-08-21T21:31:46.233 回答
1

那么你正在做双重查找。你可以这样做countshash[(cont[7],count[10])]+=1,这可能会更快,但取决于python如何实现它。内存占用应该稍大一些。

像这样简单的东西:

countshash=defaultdict(int)
for l in bigtable:
          cont = l.split()
          countshash[(cont[7],cont[10])]+= 1;
于 2012-08-21T21:03:33.700 回答