寻找最pythonic /优美的方式做到这一点:
def map_num_indexes(arr_len, tup):
ans = [0] * arr_len
for i in tup:
ans[i] = 1
return ans
print(map_num_indexes(4, (2, 3))) # [0, 0, 1, 1]
print(map_num_indexes(4, (1, 3))) # [0, 1, 0, 1]
答案 0 :(得分:3)
列表理解将起作用:
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()