Concatenate two 2D arrays in parallel

Asked

Viewed 33 times

0

How to concatenate two 2D arrays in parallel by returning an array 1D, example:

ARRAYS/LISTS

lista 1 = [['a'],['b'],['c']]

lista 2 = [['A'],['B'],['C']]

GOAL:

lista 3 = ['a:A','b:B','c:C']

Trying:

concat_array = [itm + ':' if not itm.endswith(':') else itm for itm in lista1 + lista2]
  • that, list 1 = [['a'],['b'],['c']], forgot to put simple quotes in the example

  • Goal is to get a list like this: list 3 = ['a:A','b:B','c:C']

  • changed the question...

  • where list3 = list1 + ':' + Lista2

1 answer

3


You can use the function zip to iterate over the two lists and then concatenate the first element of each sublist.

lista_1 = [['a'],['b'],['c']]
lista_2 = [['A'],['B'],['C']]

concat = [f"{x[0]}:{y[0]}" for x, y in zip(lista_1, lista_2)]

print(concat)
# ['a:A', 'b:B', 'c:C']

Code running on Repl.it


Edit:

Luis, if you need more information about zip, this answer your own question may help.

  • Very good friend, it worked, thank you !!

  • Because you asked two identical questions? This question that you made 4 days ago is practically the same.

  • in the other the list is 1D and in this and 2D, are lists within lists.

  • 2

    The concept is the same as Luis. If you understand how to solve the problem of going through the lists in parallel, accessing sublists is easy. If you are in trouble there is no problem, the community is here to help, just take care to understand the concept well so you can use it without doubt when you need it. : D If you need I can elaborate a more detailed explanation to understand what I did..

  • Opaa, thank you very much, your solution has helped me a lot already, I will read more contents on lists in python, do not need to bother !!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.