如何从大文件快速创建数组?

2024-06-17 17:22:56 发布

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

我举了个例子:

    for line in IN.readlines():
        line = line.rstrip('\n')
        mas = line.split('\t')
        row = ( int(mas[0]), int(mas[1]), mas[2], mas[3], mas[4] )
        self.inetnums.append(row)
    IN.close()

如果ffilesize==120mb,则脚本时间=10秒。这次我可以减少吗?你知道吗


Tags: inselfforcloseline例子introw
2条回答

如果你使用列表理解,你可能会获得一些速度

inetnums=[(int(x) for x in line.rstrip('\n').split('\t')) for line in fin]

以下是两个不同版本的配置文件信息

>>> def foo2():
    fin.seek(0)
    inetnums=[]
    for line in fin:
        line = line.rstrip('\n')
        mas = line.split('\t')
        row = ( int(mas[0]), int(mas[1]), mas[2], mas[3])
        inetnums.append(row)


>>> def foo1():
    fin.seek(0)
    inetnums=[[int(x) for x in line.rstrip('\n').split('\t')] for line in fin]

>>> cProfile.run("foo1()")
         444 function calls in 0.004 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.003    0.003    0.004    0.004 <pyshell#362>:1(foo1)
        1    0.000    0.000    0.004    0.004 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
      220    0.000    0.000    0.000    0.000 {method 'rstrip' of 'str' objects}
        1    0.000    0.000    0.000    0.000 {method 'seek' of 'file' objects}
      220    0.000    0.000    0.000    0.000 {method 'split' of 'str' objects}


>>> cProfile.run("foo2()")
         664 function calls in 0.006 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.005    0.005    0.006    0.006 <pyshell#360>:1(foo2)
        1    0.000    0.000    0.006    0.006 <string>:1(<module>)
      220    0.000    0.000    0.000    0.000 {method 'append' of 'list' objects}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
      220    0.001    0.000    0.001    0.000 {method 'rstrip' of 'str' objects}
        1    0.000    0.000    0.000    0.000 {method 'seek' of 'file' objects}
      220    0.001    0.000    0.001    0.000 {method 'split' of 'str' objects}


>>> 

移除readlines()

就这么做吧

for line in IN:

使用readlines可以创建文件中所有行的列表,然后访问每一行,而不需要这样做。没有它for循环只使用生成器,它每次从文件返回一行。你知道吗

相关问题 更多 >