I am looking for a “good” way to process a list in which some elements need to be expanded to several elements (only once, without expanding the results).
Standard iterative way:
i=0
while i < len(l):
if needs_expanding(l[i]):
new_is = expand(l[i])
l[i:i] = new_is
i += len(new_is)
else:
i += 1
which is pretty ugly. I could rewrite the contents to a new list with:
nl = []
for x in l:
if needs_expanding(x):
nl += expand(x)
else:
nl.append(x)
But they both seem too long. Or I could just do 2 passes and smooth the list later:
flatten(expand(x) if needs_expanding(x) else x for x in l)
def try_expanding(x)....
flatten(try_expanding(x) for x in l)
but that also doesn’t seem “right.”
Are there any other ways to do this?
source
share