Rewrite without itertools just plain python -
how rewrite piece of code doesnt use itertools (just simple python in more 1 line, without using yield)?
list(itertools.chain.from_iterable([node] * (indeg[node] + 1) node in graph.keys()))
in context itertools.chain
serves way flatten nested list (or generator)
in [266]: keys out[266]: [0, 1, 2, 3] in [267]: indeg=[6,4,2,0] in [269]: ll=[[node] * (indeg[node] + 1) node in keys] in [270]: ll out[270]: [[0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [2, 2, 2], [3]]
a simple loop same flattening is:
in [271]: result=[] in [272]: in ll: result.extend(i) in [273]: result out[273]: [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3]
i'm not aware of comprehension expression accomplish same. python cookbook(s) may have this, though convenience of chain
may have religated history.
reduce add
gives 1 line flattener:
in [285]: import operator in [286]: reduce(operator.add, ll, []) out[286]: [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3]
this repeated result += i
, lists same extend
.
working comment:
in [289]: [j in ll j in i] out[289]: [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3]
or original double iteration:
in [290]: [j node in keys j in [node] * (indeg[node] + 1)] out[290]: [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 3]
Comments
Post a Comment