[Tutor] array manipulations
Alan Gauld
alan.gauld at btinternet.com
Thu Jun 4 10:22:51 CEST 2009
"NTB" <ntb1088 at gmail.com> wrote
> array [['Food 1', 'Nutrient 1', 0.9],
> ['Food 1', 'Nutrient 2', 0.2],
> ['Food 2', 'Nutrient 1', 0.55],
> ['Food 2', 'Nutrient 2', 0.11]]
>
> into a new array that looks like this:
>
> array [['Food 1', 0.9, 0.2],
> ['Food 2', 0.55, 0.11]]
>
I'd probably use an intermediate dictionary:
>>> a = [['F1','ggh',0.9],['F1','gh',0.5],['f2','dsd',0.7]]
>>> d = {}
>>> for r in a:
... if r[0] in d: d[r[0]].append(r[2])
... else: d[r[0]] = [r[0],r[2]]
...
>>> new = [v for k,v in d.items()]
>>> new
[['F1', 0.9, 0.5], ['f2', 0.6999]]
>>>
There may be a more elegant way to handle the if/else
but its too early to think of one :-)
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list