Python arrays and sting formatting options

Aidan aweraw at gmail.com
Tue Sep 30 03:50:27 EDT 2008


Ivan Reborin wrote:
> Hello everyone,
> 
> I was wondering if anyone here has a moment of time to help me with 2
> things that have been bugging me.
> 
> 1. Multi dimensional arrays - how do you load them in python
> For example, if I had:
> -------
> 1 2 3
> 4 5 6
> 7 8 9
> 
> 10 11 12
> 13 14 15
> 16 17 18
> -------
> with "i" being the row number, "j" the column number, and "k" the ..
> uhmm, well, the "group" number, how would you load this ?
> 
> If fortran90 you would just do:
> 
> do 10 k=1,2
> do 20 i=1,3
> 
> read(*,*)(a(i,j,k),j=1,3)
> 
> 20 continue
> 10 continue
> 
> How would the python equivalent go ?
> 
> 2. I've read the help on the next one but I just find it difficult
> understanding it.
> I have;
> a=2.000001
> b=123456.789
> c=1234.0001
> 
> How do you print them with the same number of decimals ?
> (eg. 2.000, 123456.789, 1234.000)
> and how do you print them with the same number of significant
> decimals?
> (eg. 2.000001, 123456.7, 1234.000 - always 8 decimals) ?
> 
> 
> Is something like this possible (built-in) in python ?
> 
> Really grateful for all the help and time you can spare.
> 
> --
> Ivan


I'm not sure if this is applicable to your multi-dimensional list 
problem... but it sounded a bit sudoku like (with row, columns and 
groups) so I thought I'd share a bit of code of developed in regards to 
solving sudoku puzzles...

Given a list of 9 list elements, each with nine elements (lets call it 
sudoku_grid), the following list comprehensions produce lists of indexes 
into sudoku grid

vgroups = [[(x,y) for y in xrange(9)] for x in xrange(9)]
hgroups = [[(x,y) for x in xrange(9)] for y in xrange(9)]
lgroups = [[(x,y) for x in xrange(a,a+3) for y in xrange(b,b+3)]
                   for a in xrange(0,9,3) for b in xrange(0,9,3)]

where sudoku_grid[y][x] yields the value at position (x,y), assuming the 
top left corner is indexed as (0,0)

HTH



More information about the Python-list mailing list