Home > Enterprise >  Array with multiple columns formatting
Array with multiple columns formatting

Time:10-06

I have multiple arrays and I would like to combine them together so when I call a row, the 1st value of each array is shown. How can I do this?

array1 = ['happy','sad','tired']
array2 = ['oranges', 'apples', 'grapes']
array3 = ['monkeys','elephants','tigers']

array = [array1,array2,array3]

output:['happy','sad','tired'],['oranges','apples','grapes']etc...

wanted output: ['happy','oranges','monkeys'],['sad','apples','elephants']etc...

CodePudding user response:

One way that you could do it is with zip() and list comprehension to add the elements to their own list within the largest list object

output = [[item1,item2,item3] for item1,item2,item3 in zip(array1, array2, array3)]
print(output)

though this assumes that the lists are of equal length.

CodePudding user response:

All you need to do is take the transpose of the array you obtained in line 4.

array1 = ['happy','sad','tired']
array2 = ['oranges', 'apples', 'grapes']
array3 = ['monkeys','elephants','tigers']

array = [array1, array2, array3]
# take the transpose
transpose_array = list(map(lambda x:list(x), zip(*array)))

print(transpose_array)

Here, using zip(*array) simply gives the transpose of the array as a list of tuples. Therefore here I use a lambda function to convert each tuple to a list so that we obtained a list of tuples.

CodePudding user response:

Is there a reason you don't want to use numpy? That would make things very simple.

import numpy as np
array1 = ['happy','sad','tired']
array2 = ['oranges', 'apples', 'grapes']
array3 = ['monkeys','elephants','tigers']

array = np.array([array1,array2,array3]).reshape(3, -1)

Then you can access either rows or columns with indexing:

# column
array[:, 0]
# Out[224]: array(['happy', 'oranges', 'monkeys'], dtype='<U9')

# row
array[0, :]
# Out[224]: array(['happy', 'sad', 'tired'], dtype='<U9')
  • Related