How to merge multiple lists into one array

7

As a way to merge two lists into an array, where each column in the array represents one of those lists.

Example:

a = ["Laranja", "Maçã", "Uva"]
b = [40, 50, 2, 45, 56]

Expected result:

x = (["Laranja", 40], ["Maça", 50], ["Uva", 2], ["", 45], ["", 56])
    
asked by anonymous 09.11.2016 / 23:27

3 answers

2

You can use zip_longest of library itertools :

from itertools import zip_longest

a = ["Laranja", "Maçã", "Uva"]
b = [40, 50, 2, 45, 56]

x = list(zip_longest(a, b, fillvalue=''))

If you are using Python2, replace zip_longest with izip_longest .

    
09.11.2016 / 23:40
2

Well, it's really just joining the lists.

Try the following code:

a = ['Laranja', 'Maçã', 'Uva', 'Melancia', 'Limão']
b = [40, 50, 2, 45, 56, 12, 21, 12, 12, 12, 12, 12, 12, 12]

x = []

for i in range(len(a) or len(b)):
    x.append([a[i],b[i]])

print(x)

Documentation:

  • I have created the a vector with some extra strings for testing.
  • I created the b vector with more values than the other list to only merge and not mess up if it has more values.
  • I created the empty x vector to assign a dynamic value
  • I made a loop of i starting from 0 going to the joint size of the two vectors using logical function or
  • With .append I am able to add a 'cell' in the vector where, I assign to a position [valueA, valueB] and so on by creating an array of arrays
  • Print x to see the result

Result:

[['Laranja', 40], ['Maçã', 50], ['Uva', 2], ['Melancia', 45], ['Limão', 56]]

    
03.11.2017 / 17:11
1

There is a command called zip that is from the native Python library, it receives as an argument the name of the variable that stores the lists. For example:

from itertools import zip_longest

a = ["Laranja", "Maçã", "Uva"]
b = [40, 50, 2, 45, 56]

x = zip(a, b)

The only problem is that as the list has number of differentiated values it will only append up to the index that all lists have in common

    
14.11.2016 / 01:05