Reputation: 95
y = [[0,0,0],
[0,0,0]]
p = [1,2,3,4,5,6]
y[0] = p[0,2]
y[1] = p[3,4]
Returns error
I want to assign values in p
to y
, how to do that?
The answer should be y = [[1,2,3],[4,5,6]]
Thank you very much!
Upvotes: 0
Views: 646
Reputation: 48599
y = []
p = [1,2,3,4,5,6]
y.append(p[:3])
y.append(p[3:])
print y
--output:--
[[1, 2, 3], [4, 5, 6]]
If you don't specify a value in the first position of a slice, python uses 0, and if you don't specify a value in the second position of a slice, python grabs the remainder of the list.
Upvotes: 0
Reputation: 3255
Your array slicing is using the wrong syntax. It should be:
y[0] = p[0:3]
y[1] = p[3:6]
:
to slice arrays. Using ,
goes between dimensions, and p
is not a 2-dimensional array!0:2
has only elements 0
and 1
.Upvotes: 1
Reputation: 31
In Python, colon (:) is used to slice arrays: I think this is what you are looking for:
y = [[0,0,0], [0,0,0]]
p = [1,2,3,4,5,6]
y[0] = p[0:3]
y[1] = p[3:6]
Upvotes: 1