list: from 2 to 3 dimensions..looking for a nice way
Emile van Sebille
emile at fenx.com
Sat Nov 29 22:23:45 EST 2003
Sven:
> I got values from a db in this way -> [[id, date, value1, value2,
> value...],[id,date,value1,value2,value..],...]
>
> I'd like to group the arrays if they have the same id and the date
is
> nearby(+-1 sec) to one array(so that they stand for an order)->
> [[[],[],[]],[[],[],[]]]
>
> I don't mind if it would be these structure
> {id:[[],[]],id:[[],[]]}
> but in the end they should be sorted by date
How about:
---8<------
data = [
['id1', 'date4', 'val1', 'val2', 'val3'],
['id1', 'date3', 'val1', 'val2', 'val3'],
['id3', 'date2', 'val1', 'val2', 'val3'],
['id3', 'date1', 'val1', 'val2', 'val3'],
]
data.sort(lambda ii,jj: cmp(ii[1],jj[1]))
target = []
priorid = ''
for rec in data:
if rec[0] == priorid:
target[-1].append(rec)
else:
priorid = rec[0]
target.append([priorid,rec])
from pprint import pprint
pprint(target)
---8<------
This sorts by date and groups by id if adjacent. It wouldn't take
much to change the test on priorid to be near.
--
Emile van Sebille
emile at fenx.com
More information about the Python-list
mailing list