gpt4 book ai didi

python - 检查矩阵键是否按运行顺序 - python

转载 作者:太空宇宙 更新时间:2023-11-03 18:48:07 25 4
gpt4 key购买 nike

给定一个矩阵文件,第一列用作 python 字典的键(称为 docid),我应该如何读取该文件,以便在该键不按运行顺序时停止,即

  • if docid-1 > previous_docid
  • if docid < previd

我一直按照下面的代码来做,但它看起来有点冗长,有没有其他方法可以产生相同的输出? (注意:解决方案需要处理最大 20 GB 的矩阵文件。为了提供代码片段,我提供了一个小数据集)

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]

最佳答案

我看不到任何简化,因为过滤条件取决于前一个元素(使潜在的过滤迭代变得复杂)。我不认为你的代码很复杂,但你可以定义一个特殊的遍历:

def read_text(text):
for line in text.split('\n'):
docid, termid, val = map(int,line.split())
if docid < previd or docid-1 > previd:
print line # I guess this is a debug feature
return # or raise Exception("line not in running order", line)
yield (docid, termid, val)

并在您的主代码中:

for docid, termid, val in read_text(text):
docs[docid].append((termid,val))

编辑:

也许 open('myfile','r')text.split('\n') 更有效。

for line in open('myfile','r'):
do_something(line)

关于python - 检查矩阵键是否按运行顺序 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19000125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com