比较两个列表并找到不同的对

时间:2017-11-05 09:27:58

标签: python python-2.7 python-3.x

我正在尝试比较两个列表(包含不同大小的子列表)和查找另一个列表中不存在的对(括在圆括号中)。

以下是代码:

s1 = [
    [('RESOLVED - DUPLICATE', 'VERIFIED')], [('NEW', 'RESOLVED - FIXED'), ('RESOLVED - FIXED', 'VERIFIED')], [('NEW', 'RESOLVED - DUPLICATE'), ('RESOLVED - DUPLICATE', 'VERIFIED')], [('ASSIGNED', 'RESOLVED - FIXED'), ('RESOLVED - FIXED', 'VERIFIED')], [('NEW', 'RESOLVED - WONTFIX'), ('RESOLVED - WONTFIX', 'VERIFIED')], [('NEW', 'RESOLVED - INVALID'), ('RESOLVED - INVALID', 'VERIFIED')]
]

s2 = [
    [('RESOLVED - DUPLICATE', 'VERIFIED')], [('NEW', 'RESOLVED - DUPLICATE'), ('RESOLVED - DUPLICATE', 'VERIFIED')], [('NEW', 'ASSIGNED'), ('ASSIGNED', 'RESOLVED - FIXED')], [('ASSIGNED', 'RESOLVED - FIXED'), ('RESOLVED - FIXED', 'VERIFIED')], [('NEW', 'RESOLVED - WONTFIX'), ('RESOLVED - WONTFIX', 'VERIFIED')]
]

a = []

for item in s2:
    i = 0
    print item
    while (i < len(item)):
        for item1 in s1:
        print item[i]
        if item[i] not in s1:
            a.append(item[i])
        i = i + 1

print a

上述代码没有给出s2中存在但在s1中不存在的明显对 任何帮助将非常感激。谢谢!

3 个答案:

答案 0 :(得分:2)

将您的列表展平为set个对象以及它们所要求的集合操作,在这种情况下,您希望s2s1之间的差异,< / p>

>>> from itertools import chain
>>> set(chain.from_iterable(s2)).difference(chain.from_iterable(s1))
{('NEW', 'ASSIGNED')}

注意,你可能实际上想要两者之间的symmetric difference,即不在两者中的项目:

>>> set(chain.from_iterable(s1)).symmetric_difference(chain.from_iterable(s2))
{('NEW', 'RESOLVED - FIXED'), ('NEW', 'RESOLVED - INVALID'), ('NEW', 'ASSIGNED'), ('RESOLVED - INVALID', 'VERIFIED')}

答案 1 :(得分:0)

假设嵌套结构不相关且列表可以展平:

#define APP_NAME  [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]

答案 2 :(得分:0)

如果您要查找s1中不存在的s2项,则只需使用:

  

一行

print([item for item in s2 if item not in s1])
  

详述:

该列表理解与:

相同
new_list=[]
for i in s2:
    if i not in s1:
        new_list.append(i)
print(new_list)

输出:

[[('NEW', 'ASSIGNED'), ('ASSIGNED', 'RESOLVED - FIXED')]]