Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中读取大量数字_Python - Fatal编程技术网

在python中读取大量数字

在python中读取大量数字,python,Python,我试图阅读大量的数字8112,并将它们重新排列成6列。首先,我想在第一列中添加52个数字,然后在第二列中添加52个,然后在第三列中添加52个,依此类推。当我得到结果6列时,每个列包含52个数字,我想继续以相同的方式读取,直到数据结束。我试过这个: with open('file.dat') as f: line = f.read().split() for row in range(len(line)): for col in range(6):

我试图阅读大量的数字8112,并将它们重新排列成6列。首先,我想在第一列中添加52个数字,然后在第二列中添加52个,然后在第三列中添加52个,依此类推。当我得到结果6列时,每个列包含52个数字,我想继续以相同的方式读取,直到数据结束。我试过这个:

with open('file.dat') as f:
    line = f.read().split()    
    for row in range(len(line)):
        for col in range(6):
            print line[row + 52*col],   
        print  
代码没有正确读取数字,直到最后才得到。在阅读了大约7000个数字后,它正在弯腰。我得到一个索引错误:列表索引超出范围

输入文件包含如下所列的数字:

-0.001491728991-0.001392067804-0.001383514062-0.000777354202-0.000176516325-0.00066003232 0.001491728657 0.001392067465 0.00138351373 0.00077735388 0.000176516029 0.000660032023-0.001491728966-0.001392067669-0.001383513988-0.000777354111-0.00076516303-2.5350931e-05-0.000660032270.00149172835350.000777353789 0.000176516006 0.000660031981 -0.003692742099 -0.003274685372 -0.001504168916 0.003692740966 0.003274684254 0.001504167874 -0.003692741847 -0.003274685132 -0.001504168791 ...

总共8112个数字

试试这个:

with open('file.dat') as f:
    line = f.read().split()    
    for row in range(len(line)):
        for col in range(6):
            print line[row + 52*col],   
        print  
data = range(8112) # replace with input from file

col_size = 52
col_count = 6
batch_size = (col_size*col_count)
# split input into batches of 6 columns of 52 entries each
for batch in range(0,len(data),batch_size):
    # rearrange line data into 6 column format
    cols = zip(*[data[x:x+col_size] for x in range(batch,batch+batch_size,col_size)])
    for c in cols:
        print c
输出:

(0, 52, 104, 156, 208, 260)
(1, 53, 105, 157, 209, 261)
...
(50, 102, 154, 206, 258, 310)
(51, 103, 155, 207, 259, 311)
(312, 364, 416, 468, 520, 572)
(313, 365, 417, 469, 521, 573)
...
(362, 414, 466, 518, 570, 622)
(363, 415, 467, 519, 571, 623)
(624, 676, 728, 780, 832, 884)
(625, 677, 729, 781, 833, 885)
...

有一件事:你不应该把长度除以6得到行数吗?问题是,我刚才看到,在第一列中打印52个数字之后,然后在第二列中打印下一个数字,但在打印6列52个数字之后,它又开始打印第二列中的数字…您希望每列中的数字如何彼此相邻显示,垂直还是水平?前52个数字应该垂直,然后接下来的52个数字也应该垂直打印,直到6列完成,然后重新开始。我在问题中编辑了上面的一个例子。我希望这会有帮助。如果行是7852,列是5,那么列表索引超出范围,因为行[8112]7852+5*52=8112不存在。