29
So you want the difference between two lists of items.
所以你想要两个列表的区别。
first_list = [['Test.doc', '1a1a1a', 1111],
['Test2.doc', '2b2b2b', 2222],
['Test3.doc', '3c3c3c', 3333]]
secnd_list = [['Test.doc', '1a1a1a', 1111],
['Test2.doc', '2b2b2b', 2222],
['Test3.doc', '8p8p8p', 9999],
['Test4.doc', '4d4d4d', 4444]]
First I'd turn each list of lists into a list of tuples, so as tuples are hashable (lists are not) so you can convert your list of tuples into a set of tuples:
首先,我将列表的每个列表都转换成一个元组列表,这样,tuple可以是可洗的(列表不是),所以您可以将元组的列表转换为一组元组:
first_tuple_list = [tuple(lst) for lst in first_list]
secnd_tuple_list = [tuple(lst) for lst in secnd_list]
Then you can make sets:
然后你可以做集合:
first_set = set(first_tuple_list)
secnd_set = set(secnd_tuple_list)
EDIT (suggested by sdolan): You could have done the last two steps for each list in a one-liner:
编辑(sdolan建议):您可以在一行中为每个列表完成最后两个步骤:
first_set = set(map(tuple, first_list))
secnd_set = set(map(tuple, secnd_list))
Note: map
is a functional programming command that applies the function in the first argument (in this case the tuple
function) to each item in the second argument (which in our case is a list of lists).
注意:map是一个函数式编程命令,它将第一个参数中的函数(在本例中为tuple函数)应用于第二个参数中的每个项目(在我们的例子中是列表的列表)。
and find the symmetric difference between the sets:
并求出集合之间的对称差:
>>> first_set.symmetric_difference(secnd_set)
set([('Test3.doc', '3c3c3c', 3333),
('Test3.doc', '8p8p8p', 9999),
('Test4.doc', '4d4d4d', 4444)])
Note first_set ^ secnd_set
is equivalent to symmetric_difference
.
注意,first_set secnd_set等价于symmetric_difference。
Also if you don't want to use sets (e.g., using python 2.2), its quite straightforward to do. E.g., with list comprehensions:
另外,如果您不想使用集合(例如,使用python 2.2),那么就很简单了。例如,列表理解:
>>> [x for x in first_list if x not in secnd_list] + [x for x in secnd_list if x not in first_list]
[['Test3.doc', '3c3c3c', 3333],
['Test3.doc', '8p8p8p', 9999],
['Test4.doc', '4d4d4d', 4444]]
or with the functional filter
command and lambda
functions. (You have to test both ways and combine).
或者使用功能过滤器命令和lambda函数。(你必须测试这两种方式并结合)。
>>> filter(lambda x: x not in secnd_list, first_list) + filter(lambda x: x not in first_list, secnd_list)
[['Test3.doc', '3c3c3c', 3333],
['Test3.doc', '8p8p8p', 9999],
['Test4.doc', '4d4d4d', 4444]]