[Tutor] array and dictionary
Alan Gauld
alan.gauld at btinternet.com
Sun Sep 21 10:15:00 CEST 2008
"Dinesh B Vadhia" <dineshbvadhia at hotmail.com> wrote
> Hi! Say, I've got a numpy array/matrix of the form:
>
> [[1 6 1 2 3]
> [4 5 4 7 0]...
> [2 1 0 5 6]]
>
> I want to create a dictionary of rows (as the keys) mapped
> to lists of non-zero numbers in that row
Caveat, I dont know about numpy arrays.But assuming they
act like Python lists
You can get the non zeros with a comprehension
nz = [n for n in row if n != 0]
you can get the row and index using enumerate
for n,r in enumerate(arr):
So to create a dictionary, combine the elements somethng like:
d ={}
for n,r in enumerate(arr):
d[n] = [v for v in r if v !=0]
I'm sure you could do it all in one line if you really wanted to!
Also the new any() function might be usable too.
All untested....
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list