0

I'm having difficulty with this issue, so I'll describe my problem.

I have a text file that contains 81 elements, but 1 column, i.e. it's a 81x1 matrix file.

The actual elements are irrelevant.

The file contains:

0
0
0
0
-1
.
.
.

How do I read it into a 9x9 matrix list?

For every 9th element, I want to move the next element into another column, to achieve a 9x9 matrix list.

So far I have this:

rewards = []
zero_list = ["0", "0", "0", "0", "0", "0", "0", "0", "0"]
for index in range(len(zero_list)):
    rewards.append(zero_list)

Now I have a 9x9 matrix containing all 0's.

But I'm not sure exactly how to go about storing the values in my rewards list.

Thanks!

Pangu
  • 3,721
  • 11
  • 53
  • 120
  • 1
    An easy solution is to read it into a single list and then use [this question/answer](http://stackoverflow.com/q/312443/748858) to split it into chunks – mgilson Mar 12 '14 at 05:15

3 Answers3

2

Using with clause to open the file and list comprehension to reshape:

with open('a.x') as f:
     vals=list(map(int, f))
     res=[vals[i: i+9] for i in range(0, 81, 9)]
     print res

If you're using numpy, reshaping is easier:

import numpy as np
res=np.array(vals).reshape((9,9))
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
1

You can try this:

import math

zero_list = ["0", "0", "0", "0", "0", "0", "0", "0", "0"]
chunk = int(math.sqrt(len(zero_list)))

for i in xrange(0, len(zero_list), chunk)):
    print zero_list[i:i+chunk]

Mostly used way of creating array with numpy:

from numpy  import array, reshape

zero_list = ["0", "0", "0", "0", "0", "0", "0", "0", "0"]
rewards = array(zero_list)
rewards.reshape(3,3)
Sharif Mamun
  • 3,508
  • 5
  • 32
  • 51
0

There's the easy way: read it into a single list and then use this question/answer to split it into chunks.

Then there's the hard(ish) way that I'm going to describe here. The advantage of this method is that you don't need to consume the entire file ahead of time so it could save memory. In your case (81 elements), memory isn't a problem at all, but for others who might see this, maybe it is a problem. The key here is to use itertools1.

from itertools import izip_longest, imap


# itertools recipe :)
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

with open(datafilename, 'r') as fin:
    numbers = imap(int, fin)
    data = list(grouper(numbers, 9))

print data

Note that this will give you a list of tuple. If you want a list of list, change the last line:

with open(datafilename, 'r') as fin:
    numbers = imap(int, fin)
    data = [list(x) for x in grouper(numbers, 9)]

1Assuming python2.x. In python3.x, there is no imap, regular map will do just fine. Additionally izip_longest -> zip_longest.

Community
  • 1
  • 1
mgilson
  • 300,191
  • 65
  • 633
  • 696