如何用python在连续的行中找到一组数字?

2024-10-06 15:22:32 发布

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

我正在学习python,但是我的脚本还有些问题。你知道吗

我有一个类似的文件:

1 5
2 5
3 5
4 2
5 1
6 7
7 7
8 8

我想把数字对2-1连成一行打印出来,只需要在第2列中找到它们,然后,打印第1列和第2列的结果。结果类似于:

4 2 
5 1 

我试着用python来做,因为我的文件有4000000个数据。所以,这是我的剧本:

import linecache

final_lines = []
with open("file.dat") as f:
for i, line in enumerate(f, 1):
    if "1" in line:
        if "2" in linecache.getline("file.dat", i-1):
            linestart = i - 1 
            final_lines.append(linecache.getline("file.dat", linestart))
print(final_lines)

结果是:

['2\n', '2\n', '2\n']

我必须在脚本中更改什么才能符合我想要的结果?,你能给我指路吗?谢谢。你知道吗


Tags: 文件数据in脚本ifline数字dat
3条回答

我想会有用的

import re
with open("info.dat") as f:
   for match in re.findall("\d+ 2[\s\n]*\d+ 1",f.read()):
       print match

另见:https://repl.it/repls/TatteredViciousResources

另一种选择是

lines = f.readlines()
for line,nextline in zip(lines,lines[1:]):
    if line.strip().endswith("2") and nextline.strip().endswith("1"):
       print(line+nextline)

你是Python的初学者,这很好,所以我将采用更初级的方法。这是一个很大的文件,所以你最好一次读一行,只保留那一行,但实际上你需要两行来识别模式,所以保留两行。考虑以下几点:

    fp = open('file.dat')
    last_line = fp.readline()
    next_line = fp.readline()
    while next_line:
        # logic to split the lines into a pair 
        # of numbers and check to see if the 
        # 2 and 1 end last_line and next_line
        # and outputting
        last_line = next_line
        next_line = fp.readline()

这遵循良好的、可读的软件模式,并且需要最少的资源。你知道吗

使用带有enumerate的for循环和if语句来处理行,如果条件为真,则将这两行附加到列表final_lines

final_lines = []
with open('file.dat') as f:
    lines = f.readlines()
    for i,line in enumerate(lines):
        if line.split()[1] == '2' and lines[i+1].split()[1] == '1':
            final_lines.extend([line,lines[i+1]])

现在:

print(final_lines)

将返回您想要的列表。你知道吗

相关问题 更多 >