升序整数列表索引中的二进制列表 [英] Binary list from indices of ascending integer list
问题描述
我有一个从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
将布尔转换为整数.请注意,对于列表来说,in
是O(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屋!