比较2个清单清单的内容 [英] comparing contents of 2 lists of lists

查看:95
本文介绍了比较2个清单清单的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我遇到的任务:

给出2个列表列表,将其筛选为仅没有共同点的项目.例如如果内部列表相同,则将其过滤掉.如果内部列表至少有一个共同点,则也将它们过滤掉.

Given 2 lists of lists, filter them down to only items that have nothing in common. E. g. if inner lists are identical, filter them out. If inner lists have at least one item in common, also filter them out.

注意:只有一层嵌套.内部列表仅由字符串组成.我有一个可行的解决方案,但是非常混乱.寻找反馈以改进:

Note: There is only one level of nesting. The inner lists consist only of strings. I have a solution that works, but it's EXTREMELY messy. Looking for feedback to improve:

首先,我过滤掉两个列表中的确切匹配项:

First I filter out the exact matches in both lists:

l3 = filter(lambda x: x not in l2, l1)
l4 = filter(lambda x: x not in l1, l2)

最后我得到2个列表,这些列表没有完全相同的项目.现在,我要遍历内部列表,并摆脱与其他内部列表共享项目的任何内部列表.

I end up with 2 lists of lists that do not have exactly the same items. Now I want to iterate over the inner lists, and get rid of any of them that share items with any of the inner lists of the other.

我正在做

    for i in l3:
        for j in i:
            for k in l4:
                if j in k:
                    print j, k
                    removel3.append(tuple(i))
                    removel4.append(tuple(k))
    for i in l4:
        for j in i:
            for k in l3:
                if j in k:
                    removel3.append(tuple(k))
                    removel4.append(tuple(i))
    for i in list(set(removel3)):
        l3.remove(list(i))
    for i in list(set(removel4)):
        l4.remove(list(i))

(构建要从列表中删除的单独的项目列表,因为直接在迭代循环中删除会弄乱列表索引并跳过项目.必须有一种更好的方法,但我不知道.)

(building separate lists of things to remove from lists because removing directly in the iterating loop messes up list indexing and skips items. There has to be a better way of doing it, but I don't know of it.)

但是,是的.它可以完成工作,但是从元组到集合再到列表再到更多元组……听起来非常不pythonic. :)很高兴看到任何反馈!

But yeah. It gets the job done, but going from tuples to sets to lists to more tuples... sounds very nonpythonic. :) Would be happy to see any feedback!

样本输入:

l1 = [['A', 'B', 'C'], ['D', 'E'], ['F', 'G', 'H']]
l2 = [['A', 'B', 'C'], ['D', 'I'], ['K', 'L', 'M']]

完成上述所有转换后,最终得到:

After all the transformations above, end up with:

>>> l3
[['F', 'G', 'H']]
>>> l4
[['K', 'L', 'M']]

推荐答案

我认为您想要的是这样的过滤器

I think a filter like this is what you want

filter(lambda sublist:not any(set(sublist).intersection(x) for x in list2),list1)

这篇关于比较2个清单清单的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆