I would like to read a 2d array of integers from stdin (or from a file) in Python.
Non-working code:
from StringIO import StringIO
from array import array
# fake stdin
stdin = StringIO("""1 2
3 4
5 6""")
a = array('i')
a.fromstring(stdin.read())
This gives me an error: a.fromstring(stdin.read())
ValueError: string length not a multiple of item size
Several approaches to accomplish this are available. Below are a few of the possibilities.
Using an
arrayFrom a list
Replace the last line of code in the question with the following.
Now:
Con: does not preserve 2d structure (see comments).
From a generator
Note: this option is incorporated from comments by eryksun.
A more efficient way to do this is to use a generator instead of the list. Replace the last two lines of the code in the question with:
This produces the same result as the option above, but avoids creating the intermediate list.
Using a NumPy array
If you want the preserve the 2d structure, you could use a NumPy array. Here’s the whole example:
Now:
Using standard lists
It is not clear from the question if a Python list is acceptable. If it is, one way to accomplish the goal is replace the last two lines of the code in the question with the following.
After running this, we have: