Extending List Items

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)
# or
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?

+3
source share
3 answers

If you do not need random access in the list that you generate, you can also use a recording generator.

def iter_new_list(old_list):    
    for x in old_list:
       if needs_expanding(x):
           for y in expand(x):
               yield y
       else:
           yield x

new_list = list(iter_new_list(old_list))

, .

, Python L , .

+2

- , . flatten(), , . sum():

sum(expand(x) if needs_expanding(x) else [x] for x in l, [])
sum(needs_expanding(x) and expand(x) or [x] for x in l, [])
+3

The latter is probably your most pythonic, but you can try the implied loop (or in py3, generator) with a map:

flatten(map(lambda x: expand(x) if needs_expanding(x) else x, l))
flatten(map(try_expanding, l))
+2
source

Source: https://habr.com/ru/post/1731038/


All Articles