Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Appending list of arrays in Python

I have a list A containing multiple arrays of different shape. I want to append these arrays into a single array with multiple lists. But there is an error. I also show the expected output.

import numpy as np
arB=[]

A=[np.array([[ 42,  63],
[ 84,  95],
[118, 129],
[129, 140],
[140, 151],
[185, 196],
[196, 207],
[208, 219]]),np.array([[ 21,  42],
[ 63,  84],
[ 95, 106],
[106, 117],
[117, 118],
[207, 208]])]

for i in range(0,len(A)):
    for j in range(0,len(A[i])):
        for k in range(0,2):
            B=A[i,j,k]
            arB.append(B)
            B=np.array(arB)
print([B])

The error is

in <module>
    B=A[i,j,k]

TypeError: list indices must be integers or slices, not tuple

The expected output is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array([[42,  63, 84,  95, 118, 129, 129, 140, 140, 151, 185, 196, 196, 207, 208, 219],
[[ 21,  42, 63,  84, 95, 106,106, 117, 117, 118, 207, 208]])

>Solution :

Code:-

import numpy as np
arB=[]
A=[np.array([[ 42,  63],
[ 84,  95],
[118, 129],
[129, 140],
[140, 151],
[185, 196],
[196, 207],
[208, 219]]),np.array([[ 21,  42],
[ 63,  84],
[ 95, 106],
[106, 117],
[117, 118],
[207, 208]])]
for i in range(0,len(A)):
    temp=[]
    for j in range(0,len(A[i])):
        for k in range(0,2):
            B=A[i][j][k]
            temp.append(B)
    arB.append(temp)
print(type(arB))
print(arB)

This will give output:-

<class 'list'>
[[42, 63, 84, 95, 118, 129, 129, 140, 140, 151, 185, 196, 196, 207, 208, 219], [21, 42, 63, 84, 95, 106, 106, 117, 117, 118, 207, 208]]
Convert this list form into an array..!
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading