python中二维列表的遍历方式_如何在python中遍历2D列表

I have the following list:

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

and I use fowling for loop for traversing each element for grid list ->

for i in xrange(len(grid[i])):

for j in xrange(len(grid[j])):

print grid[i][j]

print "\n"

But , it don't show last row of list i.e [5,6,7,4,7]

So, which is proper war in python to Travers in 2D List?

解决方案

The proper way to traverse a 2-D list is

for row in grid:

for item in row:

print item,

print

The for loop in Python, will pick each items on every iteration. So, from grid 2-D list, on every iteration, 1-D lists are picked. And in the inner loop, individual elements in the 1-D lists are picked.

If you are using Python 3.x, please use the print as a function, not as a statement, like this

for row in grid:

for item in row:

print(item, end = " ")

print()

Output

2 6 8 6 9

2 5 5 5 0

1 3 8 8 7

3 2 0 6 9

2 1 4 5 8

5 6 7 4 7

But, in case, if you want to change the element at a particular index, then you can do

for row_index, row in enumerate(grid):

for col_index, item in enumerate(row):

gird[row_index][col_index] = 1 # Whatever needs to be assigned.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值