[英]How do I print elements of one list that are in another list?
I have 2 lists that have a few similar value, what I want is to print out the values that are only in both lists. 我有2个具有几个相似值的列表,我想要打印出仅在两个列表中的值。 I tried a list comprehension but it gives me a boolean list:
我尝试了列表理解,但它给了我一个布尔列表:
a=[2,3,1,5,7]
b=[2,5,9,3,5,10]
c=[d in a for d in b]
print (c)
from this I get the results below: 由此我得到以下结果:
[True, True, False, True, True, False]
but I wanted the numbers familiar in both lists. 但我想在两个列表中都熟悉这些数字。
You can conditionally take only the d
that are in a
from b
: 您可以有条件地仅取
b
中a
的d
:
c = [d for d in b if d in a]
# Here -----------^
let us see this code : [d in a for d in b]
, d in a
will return True
or False
because it equal to 让我们看一下这段代码:
[d in a for d in b]
, d in a
将返回True
或False
因为它等于
if d in a:
return True
else:
return False
So the result of [d in a for d in b]
is [True, True, False, True, True, False]
因此
[d in a for d in b]
的结果[d in a for d in b]
为[True, True, False, True, True, False]
The best way to wanted the numbers familiar in both lists is: 想要两个列表中都熟悉的数字的最好方法是:
a=[2,3,1,5,7]
b=[2,5,9,3,5,10]
print(list(set(a) & set(b))) # [2, 3, 5]
You could use a set
to compare the values, however I don't believe this preserves order: 您可以使用一
set
来比较值,但是我不认为这可以保留顺序:
c = set(a) & set(b)
print('\n'.join(str(i) for i in c))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.