Python使用精确位置计算文件中的行数

2024-09-30 22:20:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这很简单,但我不太明白如何使我的for循环工作。在

我的第一个文件是两列数据的长列表:

ROW    VALUE
0      165   
1      115
2      32
3      14
4      9
5      0
6      89
7      26
.       .
406369  129
406370  103

我的第二个文件是重要行号的列表:

^{pr2}$

我所要做的就是转到文件1中感兴趣的行号,然后逐行向下走,直到value列达到零。然后,输出将只是一个重要行号的列表,后跟行数,直到第一个文件为零。例如,文件#2中重要行号“1”的输出应该是3,因为有三行,然后在文件1中值达到0。谢谢你的帮助!我有一些脚本,我已经开始,可以张贴在编辑,如果这是有用的。谢谢您!在

编辑:

我开始写一些脚本:

for line in important_rows_file:
    line = line.strip().split()
    positive_starts.append(int(line[2])

countsfile = []
for line in file:
    line = line.strip().split()
    countsfile.append([line[0]] + [line[1]])

count = 0
i = 0
for i in range(0, len(countsfile)):
    for start in positive_starts:
    if int(countsfile[start + i][1]) > 0:
            count = count + 1
    else:
            count = count

。。。。不知道下一步会发生什么


Tags: 文件in脚本编辑列表forcountline
1条回答
网友
1楼 · 发布于 2024-09-30 22:20:18

这里有两种方法。在

第一种方法是在内存中为所有行号构建字典。如果a.您要反复使用相同的数据(您可以将其存储并读回)或b.您将处理第二个文件中的许多行(即,大多数行需要这样做)。第二种方法只对给定的行号执行一次性操作。在

将此作为输入文件:

ROW    VALUE
0      165
1      115
2      32
3      14
4      9
5      0
6      89
7      26
8      13
9      0

方法1。在

^{pr2}$

输出

{0: 4, 1: 3, 2: 2, 3: 1, 4: 0, 6: 2, 7: 1, 8: 0}

方法2

def get_count_for_row(row=1):
    with open("so_cnt_file.txt") as infile:
        for i in range(0, row + 2):
            next(infile)
        cnt = 0
        for line in infile:
            row, col = [int(val) for val in line.strip().split(" ") if val]
            if col == 0:
                return cnt
            cnt += 1
print get_count_for_row(1)
print get_count_for_row(6)

输出

3
2

这里有一个解决方案,在一个调用中获取所有感兴趣的行。在

def get_count_for_rows(*rows):
    rows = sorted(rows)
    counts = []
    with open("so_cnt_file.txt") as infile:
        cur_row = 0
        for i in range(cur_row, 2):
             next(infile)
        while rows:
            inrow = rows.pop(0)
            for i in range(cur_row, inrow):
                next(infile)
            cnt = 0
            for line in infile:
                row, col = [int(val) for val in line.strip().split(" ") if val]
                if col == 0:
                    counts.append((inrow, cnt))
                    break
                cnt += 1
            cur_row = row
    return counts

print get_count_for_rows(1, 6)

输出

[(1, 3), (6, 2)]

相关问题 更多 >