How to join multiple lists in a matrix

Asked

Viewed 2,556 times

7

How would a way to merge two lists into one matrix, where each column of the matrix represents one of these lists.

Example:

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

Expected result:

x = (["Laranja", 40], ["Maça", 50], ["Uva", 2], ["", 45], ["", 56])

3 answers

4

You can use the zip_longest 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 for izip_longest.

2

There is a command called zip that is from the native Python library, it takes as 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 amount of differentiated values it will only give append until the Dice that all the lists have in common

-1

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 zip(a, b):
    x.append(i)

print(x)#irá aparecer como uma lista com tupla dentro, mas se quiseres como um dicionario

y = dict(x)#desta forma irá aparecer como um dicionario
print(y)

Browser other questions tagged

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