2 Replies - 693 Views - Last Post: 05 October 2014 - 03:27 AM Rate Topic: -----

#1 Gisengryl   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 135
  • Joined: 08-September 12

List comprehension expression for column data extraction.

Posted 05 October 2014 - 01:39 AM

a = [[1,2,3],[4,5,6],[7,8,9]]

col = [x[1] for x in a]
print col



This code prints out the values of the 2nd column. But I don't understand how the List comprehension expression works.

Doesn't x[1] obtain the value of the 2nd row ? Very confused =/
Is This A Good Question/Topic? 0
  • +

Replies To: List comprehension expression for column data extraction.

#2 sepp2k   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2770
  • View blog
  • Posts: 4,429
  • Joined: 21-June 11

Re: List comprehension expression for column data extraction.

Posted 05 October 2014 - 03:06 AM

a[1] would be the second row, but x isn't a. x is a variable iterating over the elements of a (because you wrote for x in a). So in the first iteration x is equal to a[0]; on the second it's equal to a[1] and so on. So x[1] is equal to a[0][1], then a[1][1] etc.. And that is the second column.

This post has been edited by sepp2k: 05 October 2014 - 03:07 AM

Was This Post Helpful? 2
  • +
  • -

#3 Gisengryl   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 135
  • Joined: 08-September 12

Re: List comprehension expression for column data extraction.

Posted 05 October 2014 - 03:27 AM

Thanks alot for the clear explanation, I understood now.

:chinese:
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1