我是 python 和堆疊溢位的新手。我需要創建一個二進制矩陣,如果給定串列中存在客戶,則該值取 1。例如:假設一個串列為 [4,5,8]。我需要一個 10x10 的矩陣,除了矩陣 [4,5],矩陣 [5,4], 矩陣 [5,8],矩陣 [8,5] 和矩陣 [4,8], 矩陣 [8,4] 1. 有沒有一種簡單的方法可以做到這一點?謝謝你。
uj5u.com熱心網友回復:
你有:
data = [4, 5, 8]
你計算:
matrix = [[int(c in data and r in data and c != r) for c in range(10)] for r in range(10)]
你得到:
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
上面顯示的解決方案使用基于零的索引。
uj5u.com熱心網友回復:
您可以使用numpyas vectorize執行此操作,而不使用for-loop如下所示:
arr = [4,5,8]
idx = np.array(np.meshgrid(arr,arr)).T.reshape(-1,2)
#romove (4,4) , (5,5) , (8,8)
idx = idx[idx[:,0] != idx[:,1]]
mtx = np.zeros((10,10))
mtx[idx[:,0], idx[:,1]] = 1
print(mtx)
輸出:
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 1. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/342907.html
