簡體   English   中英

將元組數字映射為“一個”以列出索引:大多數pythonic方式

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

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

列表理解將執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM