[英]List comprehension double loop with if
I have two lists A
and B
where B
is a superset of A
.我有两个列表A
和B
,其中B
是A
的超集。
I would like boolean list of that specifies whether an element of A
is equal to an element of B
.我想要一个布尔列表,它指定A
的元素是否等于B
的元素。 The superset list B
is ordered.超集列表B
是有序的。
If have tried this:如果试过这个:
res = [(1 for a in A if a is b) for b in B]
According to other answers this should work.根据其他答案,这应该有效。 But in my case it returns a list of generators.. How can I end up with just a normal list.但在我的例子中,它返回一个生成器列表。我怎么能得到一个普通的列表。 Something like:就像是:
A = ['a', 'b', 'c', 'e']
B = ['a', 'b', 'c', 'd', 'e', 'f']
res = [1, 1, 1, 0, 1, 0]
The reason you get generator objects back is because you use ()
, hence those make generator expressions, which are not evaluated until you iterate through them.您返回生成器对象的原因是因为您使用了()
,因此这些生成器表达式生成器表达式,在您遍历它们之前不会对其进行评估。
What you really should be using if simple in
operator.如果操作符简单in
您真正应该使用的是什么。 Example -例子 -
>>> A = ['a', 'b', 'c', 'e']
>>> B = ['a', 'b', 'c', 'd', 'e', 'f']
>>> res = [1 if x in A else 0 for x in B]
>>> res
[1, 1, 1, 0, 1, 0]
If your usecase is more complex and you have to use is
operator to compare elements of A
and B
.如果您的用例更复杂并且您必须使用is
运算符来比较A
和B
元素。 Then you can use any()
function to iterate through the generator expression and return True
if a match is found, other False
.然后您可以使用any()
函数遍历生成器表达式并在找到匹配项时返回True
,其他False
。 Example -例子 -
res = [1 if any(a is b for a in A) else 0 for b in B]
Demo -演示 -
>>> A = ['a', 'b', 'c', 'e']
>>> B = ['a', 'b', 'c', 'd', 'e', 'f']
>>> res = [1 if any(a is b for a in A) else 0 for b in B]
>>> res
[1, 1, 1, 0, 1, 0]
Also, according to your question -另外,根据您的问题-
I would like boolean list of that specifies whether an element of A is equal to an element of B.我想要一个布尔列表,它指定 A 的元素是否等于 B 的元素。
If what you really want is a boolean (rather than 1
or 0
) , then you can simply change above examples to -如果您真正想要的是一个布尔值(而不是1
或0
),那么您可以简单地将上面的示例更改为 -
Example 1 -示例 1 -
res = [x in A for x in B]
Example 2 -示例 2 -
res = [any(a is b for a in A) for b in B]
I think what you're looking for is the intersection of the two sets, right?我想你要找的是两组的交集,对吧?
Here's the intersection of the two sets (which I highly recommend you come up with better names for next time):这是两个集合的交集(我强烈建议你下次想出更好的名字):
A = [1, 2, 3, 5, 7, 10, 12, 9]
B = [2, 6, 7]
print [x if x in B else None for x in A]
You need the "else" in there or it doesn't work.你需要那里的“其他”,否则它不起作用。
And to solve your problem literally:并从字面上解决您的问题:
res = [True if x in A else False for x in B]
I recommend you check this answer out: if/else in Python's list comprehension?我建议您查看这个答案: 在 Python 的列表理解中的 if/else?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.