如何在python中遍历2D列表 [英] How to traverse a 2D List in python

查看:139
本文介绍了如何在python中遍历2D列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下列表:

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]]

并且我使用fowling for循环遍历网格列表的每个元素->

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"

但是,它不会显示列表的最后一行,即[5,6,7,4,7]

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

那么,在python中对2D列表中的Travers合适的战争是什么?

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

Python中的for循环将在每次迭代中选择每个项目.因此,从grid二维列表中,在每次迭代中都选择一维列表.在内部循环中,选择一维列表中的各个元素.

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.

如果您使用的是Python 3.x,请使用print作为函数,而不是像这样的语句

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()

输出

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.

这篇关于如何在python中遍历2D列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆