Denver Dang
Denver Dang

Reputation: 2615

Append a list with arrays in Python

So I currently have this code:

x_tot = []
y_tot = []
z_tot = []
for i in range(0, len(cont_all)):
    x_tot.append(cont_all[i][:, 0])
    y_tot.append(cont_all[i][:, 1])
    z_tot.append(cont_all[i][:, 2])

print x_tot

In this case the cont_all is a list consisting of several arrays with x, y and z values, e.g:

array([[ -5.24,  81.67, -51.  ],
       [ -3.34,  80.73, -51.  ],
       [ -1.43,  80.24, -51.  ]])

My idea was that I would like all the x-coordinates from all the arrays/lists in one list, and y-values the same way and so forth.

But running my code above, the print out in the end gives lists with x, y, and z-values but still with arrays inside. What am I doing wrong here since it don't append everything into one list and thereby removing the arrays?

Upvotes: 0

Views: 63

Answers (2)

Luke
Luke

Reputation: 100

I just ran your code and it looks like it works fine if you remove the punctuation inside the brackets on your cont_all[i][:, _] lines. In fact, in my version of python the code does not run at all with those in there.

x_tot = []
y_tot = []
z_tot = []
for i in range(0, len(cont_all)):
    x_tot.append(cont_all[i][0])
    y_tot.append(cont_all[i][1])
    z_tot.append(cont_all[i][2])

By the end:

x_tot == [-5.24, -3.34, -1.43]
y_tot == [81.67, 80.73, 80.24]
z_tot == [-51.0, -51.0, -51.0]

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78556

You should access the items at each index at each row not slice the row like you'v done which returns a subarray instead of a number.

The multiple assignment is however easily done with:

x_tot, y_tot, z_tot = map(list, zip(*cont_all))

Or in the case of numpy arrays:

x_tot, y_tot, z_tot = cont_all.T.tolist()

Upvotes: 2

Related Questions