Printing A Column Of A 2-D List In Python
Solution 1:
[:]
is equivalent to copy.
A[:][0]
is the first row of a copy of A.
A[0][:]
is a copy of the first row of A.
The two are the same.
To get the first column: [a[0] for a in A]
Or use numpy and np.array(A)[:,0]
Solution 2:
When you don't specify a start or end index Python returns the entire array:
A[:] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Solution 3:
[:]
matches the entire list.
So A[:]
is the same as A
. So A[0][:]
is the same as A[0]
.
And A[0][:]
is the same as A[0]
.
Solution 4:
A[:]
returns a copy of the entire list. which is A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
A[:][0]
Thus selects [1, 2, 3]
.
If you want the first column, do a loop:
col = []
for row in A:
col.append(row[0])
Solution 5:
A is actually a list of list, not a matrix. With A[:][0]
You are accessing the first element (the list [1,2,3]
) of the full slice of the list A. The [:]
is Python slice notation (explained in the relevant Stack Overflow question).
To get [1,4,7] you would have to use something like [sublist[0] for sublist in A]
, which is a list comprehension, a vital element of the Python language.
Post a Comment for "Printing A Column Of A 2-D List In Python"