简体   繁体   English

如何打印一个列表中另一个列表中的元素?

[英]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 : 您可以有条件地仅取bad

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将返回TrueFalse因为它等于

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.

相关问题 如何一一打印 Python 列表中的元素? - How do I print elements in a Python list one by one? 如何检查一个列表是否包含另一个列表的 2 个元素? - How do I check if one list contains 2 elements of another list? 如何确定一个列表是否包含另一个列表中的项目,然后在 Python 中打印它们的索引 - how do I determine if one list has items contained in another list, then print their index in Python 您如何在另一个列表中按顺序查找一个列表中的元素? - How do you find the elements in one list, in that order, in another list? 如何将一个列表的元素放在另一个列表的中间? 一维战舰游戏。 (蟒蛇) - How do I place the elements of a list into the middle of another list? A one dimensional battleship game. (Python) 如何单独打印python中另一个列表中的列表项 - How do I individually print items of a list that are in another list in python 如何将元素列表与 Python 中的另一个列表列表相乘 - How do I multiply a list of elements with another list of lists in Python 如何在 Python 中按顺序将列表元素添加到另一个列表? - How do I add list elements to another list with an order in Python? 我如何有效地找到一个列表的哪些元素在另一个列表中? - How do I efficiently find which elements of a list are in another list? 如果满足条件,如何将列表元素移动到另一个列表? - How do I move list elements to another list if a condition is met?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM