Python 2.7删除列表列表中的重复元素与另一个列表列表

时间:2015-05-15 19:10:25

标签: python list python-2.7 tuples

我正在尝试获取两个列表列表并将它们相互比较。根据我的研究,我发现最接近的是How to compare a list of lists/sets in python?。我试图做一些稍微不同的事情,可能会走错路,如果是这样,请随时指出我更好,更优的方向。第一个列表将始终是基线。它应该存在于第二个子集中。因此,一个巨大的好处是能够知道第二个列表是否缺少元素,或者是否由于新元素添加到第二个。

我有两份名单I.E。

    First = [['1', 'a', 'b', 'c'], ['2', 'a', 'b', 'c', 'd']]
    Second = [['1', 'b', 'c'], ['2', 'a', 'b', 'c', 'd']]

这些数字是列表的唯一ID。我可以按照上面的说法,得到哪些是不同的元组,但这里是差异的来源。我希望最终结果保留唯一ID,然后只发现差异。 I.E否则我很难找到数百条已改变的线路,并且可能在两个地方中的一个地方发生了变化,基本上是他搜索的两倍。

    diff[['1', 'a', 'missing from second']] 

输出可以是任何东西,只要我可以保留与其相关的数据的唯一ID,并且再次知道它是否丢失或在第二个中添加更多的是奖励但是将极大地帮助。此外,如果元组效果更好,我可以使用上面链接中的答案来使用map函数。

以其他方式为例

    First = [['1', 'a', 'b'], ['2', 'a', 'b', 'c', 'd']]
    Second = [['1', 'a', 'b', 'c'], ['2', 'a', 'b', 'c', 'd']]
    diff[['1', 'c' 'added to second']

所以我想如果我要跟踪它的添加时间,那么对于上面给出的每个例子,输出可能会更好。再次,这只是我的spitballing因为我不确定什么是最佳的方式来做到这一点。

    diff_removed[['1', 'a']
    diff_added[['1','c'] 

1 个答案:

答案 0 :(得分:1)

first = {'1':['a', 'b', 'c'], '2':['a', 'b', 'c', 'd']} # the first dictionary
second = {'1':['b', 'c'], '2':['a', 'b', 'c', 'd']} # the second dictionary
result = {} # initialize a result dictionary
for key in first: # go through the keys in one of them
    # look into dictionary indexing vs the get() method
    f = set(first[key]) # make a set out of this key's values for first
    s = set(second[key]) # make a set out of this key's values for second
    # add this entry to the result -
    # will produce key:(elements in first for this ID that are not in second,
    #                   elements in second for this ID that are not in first)
    result[key] = (f-s, s-f)

这将生成包含result的{​​{1}}字典。如果您想将空{'2': (set(), set()), '1': ({'a'}, set())}更改为set,或者将其提供给漂亮的打印函数,或者将其排序,或者其他任何内容,则可以执行其他处理。

相关问题