Combining two lists into a list of several lists

For the two lists lst1 and lst2:

lst1 = ['a']
lst2 = [['b'],
        ['b', 'c'],
        ['b', 'c', 'd']]

I would like to combine them into a list of several lists with the desired output as follows:

desiredList = [['a', ['b']],
              ['a', ['b', 'c']],
              ['a', ['b', 'c', 'd']]]

Here is one of my attempts that is approaching using lst1 + lst2and list.append():

lst3 = []
for elem in lst2:
    new1 = lst1
    new2 = elem
    theNew = new1 + new2
    lst3.append(theNew)

print(lst3)

#Output:
#[['a', 'b'],
#['a', 'b', 'c'],
#['a', 'b', 'c', 'd']]

Turning around on this, I thought that another option with theNew = new1.append(new2)would do the trick. But no:

lst3 = []
for elem in lst2:
    new1 = lst1
    new2 = elem
    #print(new1 + new2)
    #theNew = new1 + new2
    theNew = new1.append(new2)

    lst3.append(theNew)
print(lst3)

# Output:
[None, None, None]

And you will get the same result with extend.

I think it should be very simple, but I'm at a loss.

Thanks for any suggestions!

0
source share
4 answers

You can achieve the desired result using itertools.zip_longestwith fillvalue:

>>> from itertools import zip_longest
>>> list(zip_longest(lst1, lst2, fillvalue=lst1[0]))
[('a', ['b']), ('a', ['b', 'c']), ('a', ['b', 'c', 'd'])]

Or if you need a list of lists:

>>> [list(item) for item in zip_longest(lst1, lst2, fillvalue=lst1[0])]
[['a', ['b']], ['a', ['b', 'c']], ['a', ['b', 'c', 'd']]]

, , lst1 , .

+1

append, lst1:

lst3 = []
for elem in lst2:
    theNew = lst1[:]
    theNew.append(new2)
    lst3.append(theNew)
print(lst3)
+1
from itertools import product

list(product(lst1,lst2))
>>>[('a', ['b']), ('a', ['b', 'c']), ('a', ['b', 'c', 'd'])]

[lst1 + [new] for new in lst2]
>>>[['a', ['b']], ['a', ['b', 'c']], ['a', ['b', 'c', 'd']]]
+1
source

This can help

desiredlist = list(map(lambda y:[lst1,y],lst2))
0
source

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


All Articles