470,830 Members | 1,676 Online

# map() return of flat tuple list

Hi,

I have a 2D array,
maybe irregular, like

arr = [[2,2,2,2],
[2,2,2,2],
[2,2,2,2]]

if tried to pull an index list
(tuples or array elements) of
all positions - via the map funtion,
but failed.

I tried to get sth. like
[
[0,0],
[0,1],
[0,2],
...
]
for each element which really exists
in the 2D array above.

What I really got, was another in-
direction for each row of arr
[
[(0, 0), (0, 1), (0, 2), (0, 3)],
[(1, 0), (1, 1), (1, 2), (1, 3)],
...
]

How can I flatten the list in place by map(),
so that the outer map hull would collect
[i,j] flat?

This is what I tried:

id = map(lambda i: map(lambda j: (i,j), range(len(arr[i]))), range(len(arr)))
print id

I tried the map solution because I'd make a
shot at another posting (find min of 2D array),
what I intended to solve by decorate/undecorate
sort.

But I didn't manage to create the flat
coordinate list in one map(map)-stroke ;-)

Regards

Mirco
Jun 22 '06 #1
3 1917 Maybe you want something like this (but this doesn't use map):

def indexes(m):
return [(r,c) for r, row in enumerate(m) for c in xrange(len(row))]

m1 = [[2,2,5],
[2,2],
[2,2,2,2]]

m2 = [[],
,
[1,2,3,4]]

print indexes(m1)
print indexes(m2)

Output:
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (2, 0), (2, 1), (2, 2), (2,
3)]
[(1, 0), (2, 0), (2, 1), (2, 2), (2, 3)]

Bye,
bearophile

Jun 22 '06 #2
Thus spoke be************@lycos.com (on 2006-06-23 00:57):
Maybe you want something like this (but this doesn't use map):
[(r,c) for r, row in enumerate(m) for c in xrange(len(row))]

Ahh, its a 'list comprehension', nice. Now,
lets see how the decorate/undecorate sort
turns out to look in Python:

arr = [
[3,3,3,3],
[3,3,3,1],
[3,3,3,3] ]
print \
sorted(
[ (j,i) for j, row in enumerate(arr) for i in xrange(len(row)) ],
lambda a,b: (arr[a][a] - arr[b][b])
)[ 0 ]
==> prints indices: (1,3)

He, this looks more like Haskell than like
Python (for me, it looks awful ;-)

I'll try to come up with at least one
map inside the comprehension, if that
works - just to avoid the dual for ;-)

Reagrds and thanks

Mirco

Jun 23 '06 #3
Mirco:
He, this looks more like Haskell than like Python (for me, it looks awful ;-)

ar = [[3,3,3,3],
[3,3,3,1],
[3,3,4,3]]

print sorted( [(r,c) for r,row in enumerate(ar) for c in
xrange(len(row))],
key=lambda (r,c): ar[r][c]
)

I don't know if operator.itemgetter can be used here, I think it's too
much complex.

With python 2.5 you can probably simplify it a little (and speed it up)
with something like:

print min( [ (r,c) for r,row in enumerate(ar) for c in xrange(len(row))
],
key=lambda (r,c): arr[r][c]
)

Bye,
bearophile

Jun 23 '06 #4

### This discussion thread is closed

Replies have been disabled for this discussion.