wesley
wesley

Reputation: 95

How to slice a array and assign values to a matrix in python?

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

Answers (3)

7stud
7stud

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

SlightlyCuban
SlightlyCuban

Reputation: 3255

Your array slicing is using the wrong syntax. It should be:

y[0] = p[0:3]
y[1] = p[3:6]
  1. Use : to slice arrays. Using , goes between dimensions, and p is not a 2-dimensional array!
  2. End slices include the start, exclude the end. So 0:2 has only elements 0 and 1.

Upvotes: 1

DryingPole
DryingPole

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

Related Questions