Home > other >  two nested list make one list
two nested list make one list

Time:01-09

Here are 2 list below

list1 = [[1,2],[3,4]]
list2 = [[11,22],[33,44]]

I tried to this

output =list(tuple(zip(i, j)) for i, j in zip(list1, list2))

But my output is not as desired.

[((1, 11), (2, 22)), ((3, 33), (4, 44))]

I want to one to one correspondence such as output like

[(1,11),(2,22),(3,33),(4,44)] 

how can I fix this?

CodePudding user response:

you can do like this as well with one for loop:

k=[]
for x,y in enumerate(list1):
    k.append(tuple(zip(y,list2[x]))[0])
    k.append(tuple(zip(y,list2[x]))[1])

#k
[(1, 11), (2, 22), (3, 33), (4, 44)]

CodePudding user response:

Your original code generates a list of tuples of tuples because you have an outer list(), a tuple(), and zip() which generates the actual tuples -- you want to get rid of that tuple() in the middle and instead just have a single list comprehension that captures all the tuples produced by zip(i, j).

You can do this by putting two for statements in the comprehension (not wrapping either in a tuple() call):

>>> list1 = [[1,2],[3,4]]
>>> list2 = [[11,22],[33,44]]
>>> [z for i, j in zip(list1, list2) for z in zip(i, j)]
[(1, 11), (2, 22), (3, 33), (4, 44)]

CodePudding user response:

Using Numpy

Try this numpy solution -

import numpy as np

np.array(list1 list2).reshape(2,-1).T.tolist()
[[1, 11], [2, 22], [3, 33], [4, 44]]

If you need the internal lists to be tuples, do this variation.

import numpy as np

list(map(tuple, np.array(list1 list2).reshape(2,-1).T))
[(1, 11), (2, 22), (3, 33), (4, 44)]

CodePudding user response:

#python program for intersection of two nested lists import itertools import functools

def GCI(lst1, lst2):

temp1 = functools.reduce(lambda a, b: set(a).union(set(b)), lst1)
temp2 = functools.reduce(lambda a, b: set(a).union(set(b)), lst2)
 
lst3 = [list(set(a).intersection(set(b)))
       for a, b in itertools.product(lst1, lst2)
       if len(set(a).intersection(set(b))) != 0]
 
lst3.extend([x] for x in temp1.symmetric_difference(temp2))
 
return lst3

Hope it helps.....

  • Related