简体   繁体   中英

Binary list from indices of ascending integer list

I have an ascending list of integers e that starts from 0 and I would like to have a binary list b whose i -th element is 1 if and only if i belongs to e .

For example, if e=[0,1,3,6] , then this binary list should be [1,1,0,1,0,0,1] , where the first 1 is because 0 is in e , the second 1 is because 1 is in e , the third 0 is because 2 is not in e , and so on.

You can find my code for that below.

My question is: is there something built-in in python for that? If not, is my approach the most efficient?

def list2bin(e):
b=[1]
j=1
for i in range(1, e[-1]+1):
    if i==e[j]:
        b.append(1)
        j+=1
    else:
        b.append(0)     
return(b)

This can be done with a list comprehension, and in case e is huge then better convert it to a set first:

>>> e = [0, 1, 3, 6]
>>> [int(i in e) for i in xrange(0, e[-1]+1)]
[1, 1, 0, 1, 0, 0, 1]

The in operator returns True/False if an item is found in the list, you can convert that bool to an integer using int . Note that for lists the in is O(N) operation, so if e is large then converting it to a set will provide you much more efficiency.

I don't think there are a built-in way to do that. But you can use List Comprehensions :

a = [ 1 if i in e else 0 for i in range(1, e[-1]+1) ]

Get fun.

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