Понимание списка будет делать:
def map_num_indexes(length, which):
unique_which = set(which)
return [1 if i in unique_which else 0 for i in range(length)]
Или, более неявно:
def map_num_indexes(length, which):
unique_which = set(which)
return [int(i in unique_which) for i in range(length)]
Вы также можете использовать numpy
:
import numpy as np
def map_num_indexes(length, which):
indices = np.arange(length)
return np.where(np.isin(indices, which), 1, 0)
Илиболее обязательно:
def map_num_indexes(length, which):
a = np.zeros(length, dtype=np.int8)
a[np.asarray(which)] = 1
return a.tolist()