[英]Select sublist if element present in second list
I have two lists: 我有两个清单:
A = [['67', '75', 'X'], ['85','72', 'V'], ['1','2', 'Y'], ['3','5', 'X', 'Y']]
B = ['X', 'Y']
I want to create a third list, C
, that have the sublists of A
which have the elements defined on B
(an / or). 我想创建第三个列表
C
,它具有A
的子列表,这些子列表具有在B
定义的元素(一个/或)。
C = [[67', '75', 'X'],['1','2', 'Y'], ['3','5', 'X', 'Y']]
I have tried: 我努力了:
C = [i for i in B if i in A]
But it didn't work, I get an empty C list. 但这没有用,我得到了一个空的C列表。 Please let me know what would be the best approach to obtain C.
请让我知道获得C的最佳方法是什么。
Use a list-comprehension that checks if any of the elements in B
is in A
: 使用列表理解来检查
B
任何元素是否在A
:
A = [['67', '75', 'X'], ['85','72', 'V'], ['1','2', 'Y'], ['3','5', 'X', 'Y']]
B = ['X', 'Y']
C = [x for x in A if any(y in x for y in B)]
# [['67', '75', 'X'], ['1', '2', 'Y'], ['3', '5', 'X', 'Y']]
C = [y for y in A for x in B if x in y]
这应该可以解决问题。
You can also use this: 您还可以使用以下命令:
C = list()
for i in A:
if B[0] in i or B[1] in i:
C.append(i)
You can also use set intersection to check if there is any element in common between the element e
(sublist) of A
and b
defined as set(B)
. 您还可以使用集合交集检查
A
和b
的元素e
(子列表)(定义为set(B)
之间是否有任何共同点。
So, 所以,
b = set(B)
C = [ e for e in A if b.intersection(set(e)) ]
#=> [['67', '75', 'X'], ['1', '2', 'Y'], ['3', '5', 'X', 'Y']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.