best way to take vertical slices from a matrix?

Darrell news at dorb.com
Tue Apr 24 20:19:34 EDT 2001


If you don't mind treating arrays as dictionaries.

ar=[(1,2,3),(4,5,6),(7,8,9)]

arD={}
for x in range(len(ar)):
    xdat=ar[x]
    for y in range(len(xdat)):
        ydat=xdat[y]
        arD[(x,y)]=ydat

def getVslice(a, x, start=0, stop= -1):
    res=[]
    while start != stop:
        value=a.get((x,start))
        if value==None:
            break
        res.append(value)
        start+=1
    return res

print arD
print getVslice(arD, 0)
print getVslice(arD, 1, 1,2)
print getVslice(arD, 2,1)

############# output
{(0, 1): 2, (2, 2): 9, (2, 1): 8, (2, 0): 7, (1, 2): 6, (0, 0): 1, (1, 0):
4, (1, 1): 5, (0, 2): 3}
[1, 2, 3]
[5]
[8, 9]

--Darrell

"mary" <mary.stern at virgin.net> wrote:
> I have a simple problem and am interested to find
> the 'best' way to do this in python:
>
> Given a list such as:
>
> x[0] = (1,2,3)
> x[1] = (4,5,6)
> x[2] = (7,8,9)
>
> what's the best way to 'take vertical slices' from this
> matrix, ie end up with:
>
> y[0] = (1,4,7)
> y[1] = (2,5,8)
> y[2] = (3,6,9)
>
> Cheers!
> Tushar.
>
>





More information about the Python-list mailing list