我有两个不同的列表(让我们称之为A和B)列表,我必须找到B中的元素,而不是A和反之。两个主列表中的列表可以是无序的,它们基本上包含字符串。我正在寻找代码或提示来解决这个问题。
编辑:我没有发布代码,因为它很愚蠢。但是,根据要求,我尝试了代码:for elem in list0:
if not (elem in list1):
for d in list1:
if not (d in list0):
/*stuff I got to do on the elements*/
EDIT2:测试案例:
A = [[a, b, c], [d, e, f]]
B = [[b, a, c], [a, o, p]]
我想执行功能(A,B)并获得返回值C = [[a,o,p]]。我也需要反之亦然,D = [d,e,f]。
答案 0 :(得分:1)
如果你的两个清单是l1和l2:
set(l1).symmetric_difference(set(l2))
或
set(l1) - set(l2)
取决于您的需求。
哪些不会工作,因为列表不可清除...如果列表中的元素是可清除的,请使用以下内容:
[list(x) for x in set([frozenset(x) for x in l1]) ^ set([frozenset(x) for x in l2])]
注意:这不会返回原始元素,重新排序列表。
答案 1 :(得分:1)
如果列表和子列表中的所有内容都是可清除的,则以下内容可以正常运行,因为set
成员资格测试和差异通常为O(1)。
a,b,c,d,e,f,o,p = 'a','b','c','d','e','f','o','p' # make these hashable things
A = [[a, b, c], [d, e, f]]
B = [[b, a, c], [a, o, p]]
def is_iterable(obj):
try:
iter(obj)
except TypeError:
return False
else:
return not isinstance(obj, basestring) # consider strings atomic
def flatten(seq):
for item in seq:
if is_iterable(item):
for subitem in flatten(item):
yield subitem
else:
yield item
print list( set(flatten(A)) - set(flatten(B)) )
print list( set(flatten(B)) - set(flatten(A)) )
输出:
['e', 'd', 'f']
['p', 'o']
答案 2 :(得分:0)
如果您输入的数据是字符串列表的列表,那么您可以使用以下内容:
diff = lambda a,b: [x for x in a if x not in b]
mergelist = lambda lVals: reduce(lambda res,x: res + x, map(tuple, lVals))
diff(mergelist(A), mergelist(B))
diff(mergelist(B), mergelist(A))
根据评论编辑:
mergelist = lambda lVals: reduce(lambda res,x: res + x, map(tuple, lVals))
diff = set(a) ^ set(b) # would contains difference between two initial lists
编辑:
A = [['a', 'b','c'], ['d','e', 'f']]
B = [['b', 'a', 'c'], ['a', 'o', 'p']]
diff = lambda a,b: [list(x) for x in map(tuple, map(sorted, a)) if x not in map(tuple, map(sorted, b))]
print diff(A, B)
print diff(B, A)