我目前正在开发一个 Python 3 项目,该项目涉及对串列串列进行多次迭代,并且我想撰写一个跳过此串列串列的特定索引的代码。特定索引存盘在单独的串列串列中。我写了一个小串列,grid
以及我不想迭代的值,coordinates
:
grid = [[0, 0, 1], [0, 1, 0], [1, 0, 0]]
coordinates = [[0, 2], [1, 1], [2, 0]]
基本上,我希望跳过每个 1 grid
(1 只是用来使相应的坐标位置更明显)。
我尝试了以下代码无济于事:
for row in grid:
for value in row:
for coordinate in coordinates:
if coordinate[0] != grid.index(row) and coordinate[1] != row.index(value):
row[value] = 4
print(grid)
预期的输出是: [[4, 4, 1], [4, 1, 4], [1, 4, 4]]
执行代码后,我收到了ValueError: 1 is not in list
.
我有两个问题:
为什么当每个
coordinate
incoordinates
包含第 0 个和第 1 个位置时,我会收到此错误讯息?有没有比使用 for 回圈更好的方法来解决这个问题?
uj5u.com热心网友回复:
您的代码有两个问题。
该
row
包含整数串列,以及value
包含这些行的值。问题是您需要访问这些值的索引,而不是值本身。您设定回圈的方式不允许这样做。.index()
回传传入自变量的第一个实体的索引;它不是使用带括号的索引的直接替代品。
这是一个执行您所描述的代码片段,解决了上述两个问题:
grid = [[0, 0, 1], [0, 1, 0], [1, 0, 0]]
coordinates = [[0, 2], [1, 1], [2, 0]]
for row in range(len(grid)):
for col in range(len(grid[row])):
if [row, col] not in coordinates:
grid[row][col] = 4
print(grid) # -> [[4, 4, 1], [4, 1, 4], [1, 4, 4]]
顺便说一句,如果您有很多坐标,则可以将其设为一组元组而不是二维串列,这样您就不必为每个行/列索引对遍历整个串列。该集合看起来像coordinates = {(0, 2), (1, 1), (2, 0)}
,并且您将使用if (row, col) not in coordinates:
而不是if [row, col] not in coordinates:
使用集合。
uj5u.com热心网友回复:
对于任何正在寻找的人来说,这是一种 numpy 方法
import numpy as np
g = np.array(grid)
c = np.array(coordinates)
mask = np.ones(g.shape, bool)
mask[tuple(c.T)] = False
#This mask skips each coordinate in the list
g[mask] =4
print(g)
[[4 4 1]
[4 1 4]
[1 4 4]]
对于那些喜欢的人来说,还有一个单行串列理解 -
[[j 4 if [row,col] not in coordinates else j for col,j in enumerate(i)] for row,i in enumerate(grid)]
[[4, 4, 1], [4, 1, 4], [1, 4, 4]]
uj5u.com热心网友回复:
grid = [
[0, 0, 1],
[0, 1, 0],
[1, 0, 0]]
coordinates = [[0, 2], [1, 1], [2, 0]]
for y, row in enumerate(grid):
for x, value in enumerate(row):
if [x, y] in coordinates or value != 1:
grid[y][x] = 4
print(grid)
0 评论