比较不相等的列表 [英] Compare unequal lists
本文介绍了比较不相等的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想比较两个不相等的列表:
I want to compare two unequal lists:
a = [6]
b = [6,7,8]
我要关注:
if list a == list b:
#do something for matching elements from both lists
else:
#do something for non-matching elements
任何建议都是有意义的.
Any suggestions are appreciative.
推荐答案
如果要查找两个列表中都存在的元素,则应理解以下列表:
If you are looking for the elements which exist in both lists, the following list comprehension should work:
c = [item for item in b if item in a]
像这样:
>>> a = [6]
>>> b = [6,7,8]
>>> c = [item for item in b if item in a]
>>> c
[6]
>>>
如果需要,说每次值匹配时都打印一些内容,请使用以下for
循环:
If you want to, say print something every time the values match, use the following for
loop:
for i in b:
if i in a:
print '%d in both sets!' %(i)
else:
print '%d does not match!' %(i)
运行方式为:
>>> a = [6, 7]
>>> b = [6, 7, 8]
>>> for i in b:
... if i in a:
... print '%d in both sets!' %(i)
... else:
... print '%d does not match!' %(i)
...
6 in both sets!
7 in both sets!
8 does not match!
>>>
这篇关于比较不相等的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文