如何比较python中的两个列表,对象实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17236801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to compare two list ,object instances in python
提问by user2481309
Say if I have:
说如果我有:
list1 = [1,6]
list2 = [1]
I want to do something if list values match!
如果列表值匹配,我想做点什么!
Compare it and do stuff after that
比较它然后做一些事情
采纳答案by óscar López
Mmm, like this?
嗯,像这样?
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.
当然,您需要澄清“如果列表值匹配”是什么意思。上面将检查两个列表是否在相同的位置具有相同的元素 - 也就是说,它们是否相等。
EDIT:
编辑:
The question is not clear, let's see some possible interpretations. To check if all elements in list1are also in list2do this:
问题不是很清楚,让我们看看一些可能的解释。要检查中的所有元素list1是否也都在,list2请执行以下操作:
if all(x in list2 for x in list1):
doStuff()
Or to do something with each element in list1that also belongs in list2, do this:
或者要对list1也属于 in 的每个元素做一些事情list2,请执行以下操作:
for e in set(list1) & set(list2):
doStuff(e)
回答by TerryA
Use any():
使用any():
>>> L1 = [1,6]
>>> L2 = [1]
>>> any(i in L1 for i in L2)
True
Pretty much, it loops through each item in L2and if any item in L2 is in L1, then it will return True.
几乎,它循环遍历中的每个项目L2,如果 L2 中的任何项目在 中L1,则它将返回True。
If you want to see whether each item is in the other list, and print which ones are and which ones aren't:
如果您想查看每个项目是否在另一个列表中,并打印哪些是,哪些不是:
>>> for i in L2:
... if i in L1:
... print i, "is in L1"
... else:
... doStuff(i)

