python - how to search efficiently items in the list? -


i have list of dicts:

[     {"num": 60, "name": "a"},      {"num": 50, "name": "b"},      {"num": 49, "name": "c"},      ... etc ] 

and list created this:

[[x, {}] x in xrange(0, mylist[0]['num'])]  list:  [..., [50, {}], [51, {}], ... , [60, {}], ...,  [65, {}], ... etc] 

and this:

[..., [50, {"num": 50, "name": "b"}], [51, {}], ..., [60, {"num": 60, "name": "a"}], ..., [65, {}], ... etc] 

how it?

in question, wrote

and this:
[..., [50, {"num": 50, "name": "b"}], [51, {}], ..., [60, {"num": 60, "name": "a"}]

the accepted answer gives different, i'd add answer more faithful original request.

this answer based on observation wrote xrange(0, mylist[0]['num']) leading me think topmost number in list in first position, , further inspection of example data showed numbers given in decreasing order... assumed in original list there order.

based on assumption, here code

# data source l0 = [{"num": 60, "name": "a"}, {"num": 50, "name": "b"}, {"num": 49, "name": "c"}]  # initialization, length of data source, void data destination, # start beginning of data source ll0, l1, nl = len(l0), [], 0  # loop downwards, because want match numbers # in data source high low n in range(l0[0]['num'], 0, -1):     # first test avoids indexerror, second test condition     if nl < ll0 , l0[nl]['num'] == n:         l1.append([n, l0[nl]])         # if had match, switch our attention next item         # in data source, hence increment index in data source         nl += 1     else:         l1.append([n, {}])  # built data destination list top bottom, # want bottom top, hence l1.reverse() 

to repeat myself, code assumes particular ordering in data source, if assumption doesn't hold i'd more happy retire answer.


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -