簡體   English   中英

基於選擇器填充對角矩陣

[英]Filling a diagonal matrix based on selectors

我有兩個清單:

[(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)]

[False, False, True, False, False, False]

第一個列表表示矩陣的row_number,column_number。 第二個列表代表元素值。 如何創建有效的循環(或其他算法),所以最終得到4 x 4矩陣:

0 0 0 0
0 0 0 0
0 1 0 0
0 0 0 0 

如果使用itertools.compress這實際上很容易:

from itertools import compress

d = [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)]   
sel = [False, False, True, False, False, False]

res = [[0 if (j, i) not in compress(d, sel) else 1 for i in range(4)] for j in range(4)]

產量:

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

Compress獲取一些數據(此處為d )和一些選擇器(此處為sel ),並保留具有對應選擇器的值為真的數據。

然后,列表推導會創建矩陣,並用零或一填充它。

我建議使用scipy模塊中的sparse庫進行有效的稀疏矩陣操作。 這是創建所需矩陣的方法:

from scipy import sparse
coo = [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)]
data = [False, False, True, False, False, False]

m = sparse.coo_matrix((data,zip(*coo)), shape=(4,4))
print(m)

請注意,還有許多其他稀疏矩陣格式(包括對角線格式),具體取決於您發現最適合創建和處理它的表示形式。

這是否必須實際上是一個類似numpy的矩陣? 在我看來,您可以執行以下操作:

coords = [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)]
values = [False, False, True, False, False, False]

DEFAULT_VALUE = 0

height, width = max(coords)[0], max(coords, key=lambda x_y:x_y[1])[1]
matrix = [[DEFAULT_VALUE for _ in range(width)] for _ in range(height)]
for coord, value in zip(coords, values):
    y, x = coord
    matrix[y][x] = value

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM