简体   繁体   中英

print a list of numbers on 6 columns python

I have a list or numbers printed like this in one line: 0.232 2.34234 ...1.2232. In total there are 156 numbers. I would like to print only 6 of them in a line like:

a b c d e f

g h i j k l

...

I have tried this so far, my numbers are in the 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]) 

However, this is still printing the numbers in one line. Can anyone help me with this, please! Thanks.

Can I print first 52 numbers in the same column and so on (still 6 columns). I have lots of numbers this time and I want to keep the first 52 and so on numbers in the same column. So in the end I have:

1 53 105 157 209 261

2

...

52 104 156 208 260 312

313 ... ... ... ... ...

...(another 52 numbers and so on)

You need to split the data on whitespace, you cannot slice characters as you will slice off parts of numbers, taking six characters is not the same as taking six of your numbers, unless you knew the exact length of each number substring then you need to separate into individual sub elements with 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)]))
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)))

if file line is range(156) output

['[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]']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM