简体   繁体   English

Python:遍历子列表

[英]Python: Iterating over sub-lists

I have a project where I am trying to edit portions of nested lists. 我有一个项目,我正在尝试编辑部分嵌套列表。 Say I started with this list: 假设我从以下列表开始:

[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]

I want to iterate over a portion of this list so that I get an output that is a square of ones in the center like so. 我想遍历此列表的一部分,以便得到这样的输出,即在中心是一个平方的输出。

[[0, 0, 0, 0, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 0, 0, 0, 0]]

I tried using a for-loop to iterate through the list and a nested for loop to iterate through the sub-lists. 我尝试使用for循环遍历列表,并使用嵌套的for循环遍历子列表。 However, that did not work. 但是,那没有用。 What I got instead was this list: 我得到的是以下列表:

[[0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0]]

Here is my code: 这是我的代码:

list = [[0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0]]

for i in range(1,4):
    for j in range(1,4):
        list[i][j] = 1

Why won't this code work? 为什么这段代码行不通? I have searched for a day or two and have not found an answer. 我搜索了一两天,却没有找到答案。 Thank you in advance to whoever takes the time to answer or comment. 预先感谢您抽出宝贵时间回答或发表评论。

The code you posted is working fine: 您发布的代码运行正常:

>>> list = [[0, 0, 0, 0, 0],
...         [0, 0, 0, 0, 0],
...         [0, 0, 0, 0, 0],
...         [0, 0, 0, 0, 0],
...         [0, 0, 0, 0, 0]]
>>> 
>>> for i in range(1,4):
...     for j in range(1,4):
...         list[i][j] = 1
... 
>>> pprint(list)
[[0, 0, 0, 0, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 1, 1, 1, 0],
 [0, 0, 0, 0, 0]]

Check that your code actually looks like what you posted here. 检查您的代码是否实际上看起来像您在此处发布的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM