Home > Net >  Keeping the structure of a list in after operating a nested loop
Keeping the structure of a list in after operating a nested loop

Time:12-24

Suppose I have two lists as follow:

x = [['a','b','c'],['e','f']]
y = ['w','x','y']

I want to add each element of list x with each element of list y while keeping the structure as given in x the desired output should be like:

[['aw','ax','ay','bw','bx','by','cw','cx','cy'],['ew','ex','ey','fw','fx','fy']]

So far I've done:

res = []
for i in range(len(x)):
    for j in range(len(x[i])):
        for t in range(len(y)):
            res.append(x[i][j] y[t])

where res produces the sums correctly but I am losing the structure, I get:

['aw','ax','ay','bw','bx','by','cw','cx','cy','ew','ex','ey','fw','fx','fy']

Also is there a better way of doing this instead of many nested loops?

CodePudding user response:

The key here is to understand list comprehension and the difference between .extend() and .append() for python lists.

output = []
for el in x:
    sub_list = []
    for sub_el in el:
        sub_list.extend([sub_el i for i in y])
    output.append(sub_list)

print(output)

CodePudding user response:

With itertools.product and builtin map functions:

import itertools

x = [['a','b','c'], ['e','f']]
y = ['w','x','y']
res = [list(map(''.join, itertools.product(i, y))) for i in x]

print(res)

The output:

[['aw', 'ax', 'ay', 'bw', 'bx', 'by', 'cw', 'cx', 'cy'], ['ew', 'ex', 'ey', 'fw', 'fx', 'fy']]
  • Related