简体   繁体   English

从索引中获取布尔列表中的真值 - python

[英]Getting True values in a boolean list from indices - python

How do I compute the inverse of what is described here: Getting indices of True values in a boolean list ?如何计算此处描述的倒数: Getting indices of True values in a boolean list That above link always comes up when I try searching for "how to obtain the true values in a boolean list from integer indices," but it gives me the indices from the true values in a boolean list, which is the inverse of what I want...当我尝试搜索“如何从整数索引中获取布尔列表中的真实值”时,上面的链接总是出现,但它为我提供了布尔列表中真实值的索引,这与我想要的相反...

For example, from:例如,来自:

t = [4, 5, 7]
count = 16

I want to obtain:我想获得:

[False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]

The values are all 0 indexed, as expected with Python.正如 Python 所期望的那样,这些值都是 0 索引的。 I'm guessing that my question is a duplicate, but it's so annoying to not be able to find what I'm looking for every time I try to remember how to do this operation, I decided to ask a new question so my Google search will hopefully bring up this post next time.我猜我的问题是重复的,但每次我试图记住如何执行此操作时都找不到我要找的东西,这太烦人了,我决定问一个新问题,所以我的谷歌搜索希望下次能提出这个帖子。

You can use a list comprehension.您可以使用列表理解。 I recommend you turn t into a set for O(1) lookup:我建议你把t变成一个 O(1) 查找的set

t_set = set(t)
res = [i in t_set for i in range(count)]

Use a list comprehension with conditions:使用带条件的列表理解:

print([True if i in t else False for i in range(count)])

Shorter:较短:

print([i in t else False for i in range(count)])

How about this:这个怎么样:

In [6]: holderplace =[False for i in range(count)]

In [7]: for i in t:
   ...:     holderplace[i-1]=True
   ...:     

In [8]: holderplace
Out[8]: 
[False,
 False,
 False,
 True,
 True,
 False,
 True,
 False,
 False,
 False,
 False,
 False,
 False,
 False,
 False,
 False]

In [9]: 

You could also try using map() :您也可以尝试使用map()

list(map(lambda x: x in t, range(count)))
# [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]

It might also be worth converting t to a set, since lookup is O(1) instead of O(N).t转换为集合也可能是值得的,因为查找是 O(1) 而不是 O(N)。

You could also use __contains__() :您还可以使用__contains__()

list(map(t.__contains__, range(count)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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