如何比较python中的两个列表,对象实例 [英] how to compare two list ,object instances in python
本文介绍了如何比较python中的两个列表,对象实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有:
list1 = [1,6]
list2 = [1]
如果列表值匹配,我想做点什么!
I want to do something if list values match!
比较之后再做事情
推荐答案
嗯,像这样吗?
if list1 == list2: # compare lists for equality
doStuff() # if lists are equal, do stuff after that
当然,您需要澄清如果列表值匹配"是什么意思.上面将检查两个列表是否在相同的位置具有相同的元素 - 也就是说,它们是否相等.
Of course, you need to clarify what do you mean by "if lists values match". The above will check to see if both lists have the same elements, in the same position - that is, if they're equal.
问题不清楚,让我们看看一些可能的解释.要检查 list1
中的所有元素是否也在 list2
中,请执行以下操作:
The question is not clear, let's see some possible interpretations. To check if all elements in list1
are also in list2
do this:
if all(x in list2 for x in list1):
doStuff()
或者对 list1
中也属于 list2
的每个元素做一些事情,这样做:
Or to do something with each element in list1
that also belongs in list2
, do this:
for e in set(list1) & set(list2):
doStuff(e)
这篇关于如何比较python中的两个列表,对象实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文