Go through list of lists and list together

I have a list of lists, well, a list whose elements can have an attribute that is a list

a =  [ob1,ob2,ob3,ob4,ob52,ob7,ob8,ob10]
ob52.list = [ob5,ob6]
ob82.list = [ob8,ob9]

      

and the list

b= [b1,b2,b3,b4,b5,b6,b7,b8,b9,b10]

      

both lists contain 10 elements, i.e. they are said to always contain the same number of elements.

What I want to do is ob[i].b = b[i]

if ob.has_list == False

for all i.
If it ob

has a list, assign each item a ob[i].list

correspondingb[i]

I solved it like this (pretty C'ish) and wondered if there is an easier way.

i=0;k=0;j=0
for k in xrange(0,len(a)):
    if k<i:
        continue
    if a[j].has_list:
        for q in a[j].list:
            q.b = b[i]
            i+=1
    else:
        a[j].b = b[i]
        i+=1
    j+=1

      

+3


source to share


1 answer


Since both lists are the same length, when a

flattened you can flatten a

, then you can usezip



import itertools

flat_a = itertools.chain.from_iterable(
            (e.list if e.has_list else (e,))
                for e in a)

for xa, xb in zip(flat_a, b):
    xa.b = xb

      

+1


source







All Articles