Print only the column of a matrix

Asked

Viewed 14,598 times

3

I’m a beginner in python and I’m having doubts about the use of list and tuple and its operators. I’m trying to print only the column of an array but I’m not getting it. I’ve tried the following to print the second column:

matriz = [[1, 5], 
          [7, 4], 
          [8, 3]]

print matriz[0:3][1]

But he is printing only the second line, as if he were print matriz[1] only. The [0:3] does not indicate that it must traverse all lines and the [1] what should print the second column? I would like to know how these operators work. I have also seen in other codes using something like matriz[0, 1] instead of matriz[0][1], however if I do not separate rows from columns with brackets, my program gives error.

4 answers

4


That’s not what that expression does. lista[inicio:fim] creates a sublist started (including) in inicio and terminated (exclusively) in fim:

>>> [0,1,2,3,4,5][1:4]
[1, 2, 3]

>>> [0,1,2][0:3]
[0, 1, 2]

Note that in this second example the list was the same (because you started at its beginning and went all the way. Similarly, in your code the returned sublist is being equal to the original matrix, and by accessing your second element you are actually taking the second line:

>>> matriz = [[1,5],
...           [7,4],
...           [8,3]]
>>> matriz[0:3]
[[1, 5], [7, 4], [8, 3]]
>>> matriz[0:3][1]
[7, 4]

If you want the second element of each matrix row, you can use an understanding of lists:

>>> [x[1] for x in matriz]
[5, 4, 3]

Then just add a loop to print them one by one:

>>> for v in [x[1] for x in matriz]:
...     print v
...
5
4
3

(although in this case it is silly to do this, just iterate on the original list and print v[1]...)

By the way, if instead of a list you have an object, you can use other complex objects (such as tuples) as keys. Then it would make sense something like matriz[0, 1], but it would be accessing a specific property of the object and not two distinct values of a nested list:

>>> x = []
>>> x[1, 2] = 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple

>>> x = {}
>>> x[1, 2] = 10
>>> x
{(1, 2): 10}

But if what you have are lists of lists, in fact it takes two uses of the brackets to access an internal element, you cannot (unfortunately...) use tuples as indexes.


Note: if it is sorely needed, you could put the print within the very understanding of lists, avoiding a loop. In Python 3 at least, I don’t know if you can do this in Python 2:

>>> [print(x[1]) for x in matriz]
5
4
3
[None, None, None]

(this last line is the list created, where each element is the return of the print - None; normally it will be ignored)

Just be careful that this creates a new list, the same size as the original (1st level), which increases memory consumption. This technique would only be recommended if you were in a context where only one expression fits (within a lambda, for example) and - concisely - you wanted to avoid creating a new function.

  • The print example is quite dirty. Why create a list with multiple None objects? While a list comprehension works well by applying another function, in the case of print it makes no sense at all, being more gambiarra and laziness to write two lines instead of one.

  • @Pablopalaces Several languages have a "for-each" that allows you to apply a function to a collection in a single expression (e.g., Javascript - matriz.forEach(function(e) { console.log(e[1]); })). Python has no such built-in, So yes, it is a trick... The question that needs to be asked is whether this trick is useful/necessary or not. As you would for example if you need to include this loop inside a lambda?

  • Which loop do you refer to? My point is, if the goal is to simply make a print, one is traditional is more appropriate. It makes no sense to generate a list (or any object) if later it will not be used, even more of None objects.

  • @Pablopalaces I understand, my point is that if you need to do such an operation in a context where you expect only an expression - and not a set of instructions (statements) - You can’t. The fact that there is a way to do this, even if it is done by the police, is something that increases the expressiveness of the language. But it is logical that if you are in a context where an instruction is expected, it is best to opt for clarity, as you suggest (and in that case I would not use any list understanding, only one for where if the print uses x[1]).

  • 1

    I did, but as long as that context is not the issue, I wouldn’t put that kind of example where someone with little experience can just copy and paste out of context. Imagine if the OP has a giant list, at the end of that he ends up with two giant lists can get problems with that.

  • @Pablopalaces You’re right! I edited the answer by moving this piece pro final and explaining its purpose and limitations better.

Show 1 more comment

2

Imagine your matrix is a table and you have an Axis: x and y:

     0 1
   .-----> x
0  | 1 5
1  | 7 4
2  | 8 3
   V
   y

If you want to access the position 7 (x=>0,y=>1). Just do it through the indexes:

matriz[1][0];

That in theory would be something represented by:

 matriz[y][x]

1

To work with matrices, it’s nice to use numpy.

With it you can do:

>>> import numpy as np
>>> a = np.array([[1, 5], [7, 4], [8, 3]])
>>> print a.transpose()[0]
[1 7 8]

1

Save Andre you want something like this:

>>> matriz = [[1, 5], 
...           [7, 4], 
...           [8, 3]]
>>> for m in matriz:
...     print m[1]
... 
5
4
3
>>> 

If you want the first column just change m[0]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.