如何返回布尔值列表以查看一个列表中的元素是否在另一列表中 [英] How to return list of booleans to see if elements of one list in another list

查看:54
本文介绍了如何返回布尔值列表以查看一个列表中的元素是否在另一列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表:

A = [1,2,3,4,5,6,7,8]
B = [2,3,4]

,并希望获得一个length(A)的布尔列表,其中每个索引处的元素指示A中相同索引处的元素是否在列表B中的任何位置.返回值将是:

and want to get a boolean list of length(A) where the element at each index indicates whether the element at the same index in A is in anywhere in the list B. The return value would be:

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

编写一个函数很容易,但是想知道在Python中是否有一种范式来实现它.

It would be easy to write a function, but want to know if there is a paradigmatic way of doing it in Python.

在R中,对应的是

which(A %in% b)

推荐答案

使用列表理解:

In [164]: A = [1,2,3,4,5,6,7,8]

In [165]: B = [2,3,4]

In [166]: [x in B for x in A]
Out[166]: [False, True, True, True, False, False, False, False]

如果 B 很大,那么最好先将其转换为 set .因此,集合的成员资格测试为 O(1)与列表中的 O(n)相比.

If B is huge then better convert it to a set first. As, membership test for sets is O(1) compared to O(n) in lists.

In [167]: b=set(B)

In [168]: [x in b for x in A]
Out[168]: [False, True, True, True, False, False, False, False]

这篇关于如何返回布尔值列表以查看一个列表中的元素是否在另一列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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