升序整数列表索引中的二进制列表 [英] Binary list from indices of ascending integer list

查看:71
本文介绍了升序整数列表索引中的二进制列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从0开始的整数e的升序列表,并且我想有一个二进制列表b,当且仅当i属于e时,其第i个元素为1.

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.

例如,如果e=[0,1,3,6],则此二进制列表应为[1,1,0,1,0,0,1], 其中第一个1是因为0在e中,第二个1是因为1在e中, 第三个0是因为2不在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.

我的问题是:是否在python中内置了某些功能?如果不是,是我的 方法最有效?

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)

推荐答案

这可以通过列表理解来完成,如果e很大,则最好先将其转换为set:

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]

如果在列表中找到一个项目,in运算符将返回True/False,您可以使用int将布尔转换为整数.请注意,对于列表来说,inO(N)操作,因此,如果e很大,那么将其转换为集合将为您提供更高的效率.

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.

这篇关于升序整数列表索引中的二进制列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆