将元组数字映射为“ 1”列出索引:大多数pythonic方式

时间:2019-02-25 04:42:17

标签: python python-3.x list indexing tuples

寻找最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]

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()