给定一个矩阵文件,并且第一列用作python字典的键(称为docid),我应该如何读取该文件,以便在该键未按运行顺序运行时停止,即
if docid-1 > previous_docid
或if docid < previd
我一直按照下面的代码来做,但看起来有点冗长,有没有其他方法可以产生相同的输出(注意:解决方案需要处理高达20GB的矩阵文件。为了获得代码片段,我给出了一个小数据集)
text = '''0 1 1
0 2 1
1 3 1
1 7 1
2 5 4
2 4 6
2 9 8
3 5 7
3 9 8
3 10 9
9 2 9
9 8 3
3 9 4'''
from collections import defaultdict
docs = defaultdict(list)
previd = -1
for line in text.split('\n'):
docid, termid, val = map(int,line.split())
if docid < previd or docid-1 > previd:
print line
break
previd = docid
docs[docid].append((termid,val))
for i in docs:
print i, docs[i]
我看不到任何简化,因为过滤条件取决于前面的元素(使潜在的过滤迭代变得复杂)。我认为您的代码并不复杂,但您可以定义一个特殊的遍历:
在主代码中:
编辑:
也许
text.split('\n')
比open('myfile','r')
更有效相关问题 更多 >
编程相关推荐