简体   繁体   中英

Mapping tuple numbers to list indexes as “ones”: most pythonic way

Looking for the most pythonic/graceful way of doing this:

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]

A list comprehension will do:

def map_num_indexes(length, which):
    unique_which = set(which)
    return [1 if i in unique_which else 0 for i in range(length)]

Or, more implicitly:

def map_num_indexes(length, which):
    unique_which = set(which)
    return [int(i in unique_which) for i in range(length)]

You can also use numpy :

import numpy as np

def map_num_indexes(length, which):
    indices = np.arange(length)
    return np.where(np.isin(indices, which), 1, 0)

Or, more imperatively:

def map_num_indexes(length, which):
    a = np.zeros(length, dtype=np.int8)
    a[np.asarray(which)] = 1
    return a.tolist()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM