[英]Diagonal of a nested list in Python 3
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. 我已经尝试了嵌套的for循环的各种组合,但是似乎无法绕开它。
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. 除了[2-i]
您还可以使用[-i-1]
,它可以缩放为任意大小的正方形。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.