2014-10-01 82 views
0

我有一个巨大的整数文本文件。我需要逐行处理它们并根据每行中的数字计算将它们保存在单独的列表中加载一个巨大的文本文件

最终目标是将数字(第1行除外)加载到两个列表中 - A =奇数位置B =号码在偶数位置

文件样本:

1 3 4 5 
3 4 56 73 
3 4 5 6 

目前我做的是:

with open(filename) as f: 
    for line in f: 
     line = line.split() 
     line_num = line_num + 1 
     if line_num == 1: 
      # do something 
      pass 
     if line_num > 1: 
      line = [int(i) for i in line] 
      for x in range(len(line)): 
       # do something 
       pass 

的问题是,它正在很多的时间。有没有更好的方法来做到这一点?

+3

你确定这是不是你说的处理需要很长时间?运行需要多长时间?如果你评论你的计算需要多长时间? – Joe 2014-10-01 13:34:12

+0

我需要逐行阅读才能处理它。如果我删除了计算,则只需要更少的时间。但是,如何提高逐行读取的性能? – 2014-10-01 13:41:20

+0

@NEW_PYTHON_LEARNER你已经在阅读文件行:http://stackoverflow.com/questions/8009882/how-to-read-large-file-line-by-line-in-python – 2014-10-01 13:43:16

回答

0

而不是每次检查行是否是第一行,在开始处理第一行。不需要检查循环内部。

with open(filename) as f: 
    line = next(f) 
    # do something for the first line 

    # handle rest lines 
    for line in f: 
     line = line.split() 
     line = [int(i) for i in line] 
     for field in line: 
      # do something with field 
      pass 

我删除line_num,因为在原始代码中没有用处。但是,如果你需要它,使用enumerate

with open(filename) as f: 
    line = next(f) 

    for line_num, line in enumerate(f, 2): 
     ... 
+0

这将如何提高性能? – Andrey 2014-10-01 13:55:58

+0

@Andrey,它不会大幅提升性能。我想让OP知道循环内的检查是不需要的。 – falsetru 2014-10-01 13:57:55

1

听起来像一个有效率的numpy的:

X = numpy.loadtxt(filename) #can specify if you know for sure all are integers 
odds = X[1::2] 
evens = X[::2]