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

时间:2013-04-22 23:22:57

标签: python list for-loop count

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

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

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

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

1
43
192
so on

我想要做的就是转到文件1中感兴趣的行号,然后逐行向下走,直到值列达到零。然后输出将只是一个重要行号的列表,后面跟着第一个文件达到零之前的行数。例如,文件#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

....不确定下一步是什么

1 个答案:

答案 0 :(得分:0)

以下是两种方法。

第一种方法在内存中为所有行号构建字典。如果这样做,这将是一个很好的方法。您将一遍又一遍地重复使用相同的数据(您可以存储并重新读取)或b。您将从第二个文件处理大量行(即大多数行需要这样做)。第二种方法只对给定的行号进行一次性。

将此作为输入文件:

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

方法1。

ref_dict = {}
with open("so_cnt_file.txt") as infile:
    next(infile)
    cur_start_row = 0
    cur_rows = []
    for line in infile:
        row, col = [int(val) for val in line.strip().split(" ") if val]
        if col == 0:
            for cur_row in cur_rows:
                ref_dict[cur_row] = row - cur_row - 1
            cur_start_row = row
            cur_rows = []
            continue
        cur_rows.append(row)
print ref_dict

<强>输出

{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)]