我在一行中打印了一个或多个这样的列表:0.232 2.34234 ... 1.2232。总共有156个数字。我想在一行中只打印其中的6个:
a b c d e f
g h i j k l
...
到目前为止我已尝试过这个,我的数字在line.dat:
with open('line.dat') as file:
File = file.readlines()
for i in range(len(File)/6+1):
print ''.join(File[i*6:(i+1)*6])
然而,这仍然是在一行中打印数字。请有人帮我这个!感谢。
我可以在同一列中打印前52个数字,依此类推(仍然是6列)。这次我有很多数字,我想在同一列中保留前52个等数字。所以最后我有:
1 53 105 157 209 261
2
...
52 104 156 208 260 312
313 ...... ...... ...... ......
......(另外52个数字等等)
答案 0 :(得分:1)
你需要split
空格上的数据,你不能切割字符,因为你会切掉部分数字,取六个字符与取六个数字是不一样的,除非你知道确切的长度然后,您需要使用split:
with open('line.dat')) as f:
line = f.read().split()
print("\n".join([" ".join(line[i:i+6]) for i in xrange(0, len(line)-5, 6)]))
答案 1 :(得分:1)
import itertools as it
with open('data') as f:
lines = f.readlines()
k = lines[0].split()
i = iter(k)
for j in range(len(k) // 6):
print(list(it.islice(i, 0, 6)))
如果文件行是范围(156) 的输出强>
['[0,', '1,', '2,', '3,', '4,', '5,']
['6,', '7,', '8,', '9,', '10,', '11,']
['12,', '13,', '14,', '15,', '16,', '17,']
['18,', '19,', '20,', '21,', '22,', '23,']
['24,', '25,', '26,', '27,', '28,', '29,']
['30,', '31,', '32,', '33,', '34,', '35,']
['36,', '37,', '38,', '39,', '40,', '41,']
['42,', '43,', '44,', '45,', '46,', '47,']
['48,', '49,', '50,', '51,', '52,', '53,']
['54,', '55,', '56,', '57,', '58,', '59,']
['60,', '61,', '62,', '63,', '64,', '65,']
['66,', '67,', '68,', '69,', '70,', '71,']
['72,', '73,', '74,', '75,', '76,', '77,']
['78,', '79,', '80,', '81,', '82,', '83,']
['84,', '85,', '86,', '87,', '88,', '89,']
['90,', '91,', '92,', '93,', '94,', '95,']
['96,', '97,', '98,', '99,', '100,', '101,']
['102,', '103,', '104,', '105,', '106,', '107,']
['108,', '109,', '110,', '111,', '112,', '113,']
['114,', '115,', '116,', '117,', '118,', '119,']
['120,', '121,', '122,', '123,', '124,', '125,']
['126,', '127,', '128,', '129,', '130,', '131,']
['132,', '133,', '134,', '135,', '136,', '137,']
['138,', '139,', '140,', '141,', '142,', '143,']
['144,', '145,', '146,', '147,', '148,', '149,']
['150,', '151,', '152,', '153,', '154,', '155]']