python deque/list filtering -
i have list of actions database. copied deque since want deal in order, popping stuff off left go.
so have actions = deque(actions) fine.
each action item list psycopg module using dictcursor. each list has item 'phase'.
so things go in phases. actions in phase 'a', in phase 'b', etc. not best way store data that's given.
so make life easier want split deque several deques phase.
so if actions[0]['phase'] == 'a' goes in list containing items phase a, , on with, b, etc.
i bunch of ifs , appending seems lot of effort. think answer might filter(), i'm not sure how use it.
random stuff note:
- each item in order, order needs preserving within each deque.
- the phases known , sequential. example, if phase c doesn't exist, know phase d doesn't exist. there finite number of phases, 5 if recall.
clarification attempt:
i have deque, actions. like:
actions = [ ['phase': 'a', 'something_else': 'x'], ['phase': 'a', 'something_else': 'y'], ['phase': 'b', 'something_else': 'x'] ]
want end (something like):
a = [ ['phase': 'a', 'something_else': 'x'], ['phase': 'a', 'something_else': 'y'] ] b = [ ['phase': 'b', 'something_else': 'x'] ]
with minimal amount of code, , works number of phases/items in phases/etc.
first define key function returns phase when given action, e.g.
key = lambda action: action["phase"]
now first sort key
-- not rearrange order more necessary, i.e. order conserved each phase (it's "stable") -- use groupby
itertools
this:
from itertools import groupby actions.sort(key=key) results = [] phase, action_iterable in groupby(actions, key=key): action_list = list(action_iterable) action_list.reverse() results.append((phase, action_list)))
as see i've reversed lists. can efficiently pop off end of lists instead of using popleft on deque. if prefer, turn them deque instead of reversing. use this:
for phase, actions in results: while actions: action = actions.pop() # etc...
Comments
Post a Comment