1

I have a several lists within a list which forms a game of noughts and crosses:

list = [
        ['X', 'O', 'O'], 
        ['O', 'X', 'O'], 
        [' ', 'X', ' ']
       ]

I need to write a function that returns the diagonals of the game from top left to bottom right and then top right to bottom left so the output would be:

diags = (['X', 'X', ' '],['O', 'X', ' '])

I have tried various combinations of nested for loops, can't seem to get my head around it though.

perror
  • 7,071
  • 16
  • 58
  • 85
  • See this answer, which I think covers your question: http://stackoverflow.com/a/15100815/399704 – Aaron D Apr 01 '13 at 02:53
  • possible duplicate of [checking diagonals in 2d list (Python)](http://stackoverflow.com/questions/15100735/checking-diagonals-in-2d-list-python) – jamylak Apr 01 '13 at 03:13

1 Answers1

3
nw_to_se = [your_list[i][i] for i in range(3)]
ne_to_sw = [your_list[i][2-i] for i in range(3)]
diags = (nw_to_se, ne_to_sw)

Instead of [2-i] you could also use [-i-1], which scales to any size square.

Amber
  • 507,862
  • 82
  • 626
  • 550
  • I had to change ne_to_sw = [your_list[2-i][i] for i in range(3)] to ne_to_sw = [your_list[i][2-i] for i in range(3)] for it to be in the correct order. Thank you very much though! – user2201797 Apr 01 '13 at 03:25