python - Create set and lists with the positions in the set efficently -
i need create set of ids of messages, , positions in original list. code used sort messages later handle them according id.
the following works, readable, slow.
import numpy np ids=np.array([354,45,45,34,354])#example, actual array huge dict={} counter in xrange(len(ids)): try: dict[ids[counter]].append(counter) except: dict[ids[counter]]=[counter] print(dict) #{354: [0, 4], 34: [3], 45: [1, 2]}
any ideas how speed up? there no need lists sorted. later in code used follows, , after dict discarded
for item in dict.values(): position_of_id=position[np.array(item)] ...
try use defaultdict
, enumerate
:
from collections import defaultdict dict = defaultdict(list) i,id in enumerate(ids): dict[id].append(i)
(using try
, except
bad idea if exceptions aren't rare)
Comments
Post a Comment