如果我有一個二維串列,如何為該二維串列中的特定元素生成索引串列?
例如,如果我有串列
two_d_list = [[0, 1, 0, 0], [1, 1, 0, 0], [0, 0, 0, 1]]
我怎么能用這種格式制作一個串列
index_list = [[0, 1], [1, 0], [1, 1], [2, 3]]
這是 中所有 1 的二維索引串列two_d_list。的格式
index_list = [(0, 1), (1, 0), (1, 1), (2, 3)]
也會作業。我只需要檢索索引。
uj5u.com熱心網友回復:
two_d_list = [[0, 1, 0, 0], [1, 1, 0, 0], [0, 0, 0, 1]]
result = []
for i in range(len(two_d_list)):
for j in range(len(two_d_list[i])):
if two_d_list[i][j] == 1:
result.append((i, j))
print(result)
結果:
[(0, 1), (1, 0), (1, 1), (2, 3)]
uj5u.com熱心網友回復:
使用串列理解:
>>> [(r, c) for r, line in enumerate(two_d_list) for c, num in enumerate(line) if num==1]
[(0, 1), (1, 0), (1, 1), (2, 3)]
uj5u.com熱心網友回復:
使用串列串列可能很麻煩而且很慢。如果您能夠numpy在應用程式中使用陣列,該解決方案將變得非常簡單和快速。
import numpy as np
two_d_list = [[0, 1, 0, 0], [1, 1, 0, 0], [0, 0, 0, 1]]
# Create a numpy array
arr = np.array(two_d_list)
# np.where implements exactly the functionality you are after
# then you stack the two lists of indices and transpose
indices = np.stack(np.where(arr == 1)).T
print(indices)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/324835.html
下一篇:如何檢查行是否包含在另一行中?
