Home > Software design >  How to join lists inside two or more different lists in arranged order?
How to join lists inside two or more different lists in arranged order?

Time:11-27

I have three lists as follows.

A = [1, 2, 3]; B = [[3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3]]; C = [[2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]

I want to create another list containing all the above inner lists starting from A to C.

Desired = [elements of A, elements of B, elements of C] just like this.

Desired = [[1, 2, 3], [3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3], [2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]

CodePudding user response:

The method I use below is to see if the inner_list contents are infact a list of themselves.

  • If they are, then append the inner list.
  • If they are not, then append the outer_list.
A = [1, 2, 3]; 
B = [[3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3]]; 
C = [[2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]

desired = []

for outer_list in (A,B,C):
    list_state = False
    for inner_list in outer_list:
        if isinstance(inner_list, list):
            desired.append(inner_list)
        else:
            list_state = True
    
    # Add outer_list only if the inner_list was not a list
    if list_state:
        desired.append(outer_list)
        
print(desired)

OUTPUT:

[[1, 2, 3], [3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3], [2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]

CodePudding user response:

I made something to make a list to an nested list if it is not.

A = [1, 2, 3]
B = [[3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3]]
C = [[2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]
listt = [ 'A', 'B', 'C' ]
des = []

for i in listt:
    if type((globals()[i])[0]) != list:
        globals()[i] = [[i for i in globals()[i]]] #turns into nested list if not (line 7-9)

for i in (A,B,C):
    for x in i:
        des.append(x)

print(des)

Output:

[[1, 2, 3], [3, 4, 5], [4, 5, 6], [4, 5, 7], [7, 4, 3], [2, 3, 1], [2, 3, 3], [2, 4, 5], [4, 5, 6], [7, 3, 1]]
  • Related