我正在学习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']
我必须在脚本中更改什么才能符合我想要的结果?,你能给我指路吗?谢谢。你知道吗
我想会有用的
另见:https://repl.it/repls/TatteredViciousResources
另一种选择是
你是Python的初学者,这很好,所以我将采用更初级的方法。这是一个很大的文件,所以你最好一次读一行,只保留那一行,但实际上你需要两行来识别模式,所以保留两行。考虑以下几点:
这遵循良好的、可读的软件模式,并且需要最少的资源。你知道吗
使用带有
enumerate
的for循环和if
语句来处理行,如果条件为真,则将这两行附加到列表final_lines
:现在:
将返回您想要的列表。你知道吗
相关问题 更多 >
编程相关推荐