以下是一个示例代码,演示了如何遍历嵌套循环并删除满足条件的特定索引:
# 创建一个示例列表
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 定义要删除的特定索引
indexes_to_remove = [(0, 0), (1, 2)]
# 遍历嵌套循环
for i in range(len(nested_list)):
for j in range(len(nested_list[i])):
# 检查当前索引是否需要删除
if (i, j) in indexes_to_remove:
# 删除满足条件的特定索引
del nested_list[i][j]
# 打印结果
print(nested_list)
输出结果为:
[[2, 3], [4, 5], [7, 8, 9]]
在这个示例中,我们首先创建一个嵌套列表nested_list
,然后定义要删除的特定索引indexes_to_remove
。然后,我们使用两个嵌套的for
循环来遍历nested_list
的每个元素。在每次迭代中,我们检查当前索引是否在indexes_to_remove
中,如果是,则使用del
语句删除该索引对应的元素。最后,我们打印修改后的nested_list
。
下一篇:遍历嵌套映射