我目前正在開發一個 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.
我有兩個問題:
為什么當每個
coordinateincoordinates包含第 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/405894.html
標籤:
上一篇:如何實作可迭代結構?
