我有一個數字陣列,對應于另一個陣列的索引。
index_array = np.array([2, 3, 5])
我想要做的是用 numbers 創建另一個陣列0, 1, 4, 6, 7, 8, 9。我的想法是:
index_list = []
for i in range(10):
if i not in index_array:
index_list.append(i)
這可行,但我不知道是否有更有效的方法來做到這一點,甚至是內置函式。
uj5u.com熱心網友回復:
您可以使用它numpy.setdiff1d來有效地從不在索引陣列中的“通用陣列”中收集唯一值。通過assume_unique=True提供了一個小的加速。當assume_unique是True時,只要輸入已排序,結果就會被排序。
import numpy as np
# "Universal set" to take complement with respect to.
universe = np.arange(10)
a = np.array([2,3,5])
complement = np.setdiff1d(universe, a, assume_unique=True)
print(complement)
結果是
[0 1 4 6 7 8 9]
uj5u.com熱心網友回復:
可能最簡單的解決方案就是從集合中洗掉不需要的索引:
n = 10
index_array = [2, 3, 5]
complement = np.delete(np.arange(n), index_array)
uj5u.com熱心網友回復:
您也可以通過簡單的串列理解來做到這一點:
import numpy as np
index_array = np.array([2, 3, 5])
n = 10
complement = np.array([i for i in range(10) if i not in index_array])
print(complement)
輸出:
[0 1 4 6 7 8 9]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/449865.html
下一篇:沿numpy陣列不同軸的零件規格
