1

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...

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! It works, but I have a lot of data being processed and it has a slight delay
1

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.

Comments

0

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')

1 Comment

Thank you. I did not know about np.array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.