简体   繁体   English

用Python将另一个列表中的任何项目

[英]Python any item from a list in another list

What is an elegant way to return a list of T/F for a list if matches a list of items? 如果匹配项列表,则返回T / F列表的最佳方法是什么?

For example: 例如:

[1,3,5,4]
in
[4,3,7,5,8]

Returns: 返回值:

[True, True, False, True, False]

Testing membership in a set is O(1), while testing membership in a list is O(n). 测试集合中的成员资格为O(1),而测试列表中的成员资格为O(n)。 So (especially for a big list) you should convert firstlist to a set before testing for membership. 因此(特别是对于大列表而言),您应该在测试成员资格之前将firstlist列表转换为集合。

firstset = set(firstlist)
[(v in firstset) for v in otherlist]

Use List Comprehension: - 使用列表理解:-

>>> list1 = [4, 3, 7, 5, 8]
>>> list2 = [1, 3, 5, 4]
>>> new_list = [elem in list2 for elem in list1]
>>> new_list
[True, True, False, True, False]
>>> 

通过使用列表理解:

[(v in firstlist) for v in otherlist]

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

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