9

I have a variable data that is of (1000L, 3L) shape and I do the following to get the coordinates:

x = data[:,0]
y = data[:,1]
z = data[:,2]

Is there a way to unpack them? I tried but it doesn't work:

[x,y,z] = data1[:,0:3]

3 Answers 3

16

You could simply transpose it before unpacking:

x, y, z = data.T

Unpacking "unpacks" the first dimensions of an array and by transposing the your array the size-3 dimension will be the first dimension. That's why it didn't work with [x, y, z] = data1[:, 0:3] because that tried to unpack 1000 values into 3 variables.

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

Comments

3

You could unpack using zip:

x, y, z = zip(*data[:, :3])

Comments

0

those days, seems python 3.9 support it now.

  • x,y = arr
  • [x,y] = arr
  • foo( *arr )

Python 3.9.2

>>> a=[1,2]

>>> x,y=a
>>> x
1
>>> y
2
>>> x,y=*a
  File "<stdin>", line 1
SyntaxError: can't use starred expression here

>>> [x,y]=a
>>> x
1
>>> y
2

>>> def foo(a,b): print(a,b)
... 
>>> foo(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() missing 1 required positional argument: 'b'

>>> test1(*a)
1 2

Comments

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.