Python:两个列表列表的交集

时间:2014-02-20 22:01:20

标签: python

我有一个列表A列表和一个列表B,其中AB有许多相同的子列表。

B进入A获取唯一子列表的最佳方法是什么?

A = [['foo', 123], ['bar', np.array(range(10))], ['baz', 345]]
B = [['foo', 123], ['bar', np.array(range(10))], ['meow', 456]]

=> A = [['foo', 123], ['bar', np.array(range(10))], ['baz', 345], ['meow', 456]]

我试过了:

A += [b for b in B if b not in A]

但是这给了ValueError使用any()all()的说法。我是否真的必须逐个元素地测试BA中每个子列表中每个子列表的元素?

ERROR: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

2 个答案:

答案 0 :(得分:1)

通常情况下,您可以使用多种方法之一来按顺序或不按顺序统一列表或多个列表。

这是一种统一两个不维护顺序的列表的方法:

>>> A=[1,3,5,'a','c',7]
>>> B=[1,2,3,'c','b','a',6]
>>> set(A+B)
set(['a', 1, 'c', 3, 5, 6, 7, 2, 'b'])

这是一种维持秩序的方式:

>>> seen=set()
>>> [e for e in A+B if e not in seen and (seen.add(e) or True)]
[1, 3, 5, 'a', 'c', 7, 2, 'b', 6]

问题是所有元素都必须可以使用这些方法:

>>> set([np.array(range(10)), 22])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'

解决这个问题的一种方法是使用每个元素的repr

>>> set([repr(e) for e in [np.array(range(10)), 22]])
set(['22', 'array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])'])

或使用frozenset

>>> set(frozenset(e) for e in [np.array(range(10)), np.array(range(2))])
set([frozenset([0, 1]), frozenset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])])

在您的情况下,冻结集方法不适用于列表列表:

>>> set(frozenset(e) for e in [[np.array(range(10)), np.array(range(2))],[np.array(range(5))
]])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <genexpr>
TypeError: unhashable type: 'numpy.ndarray'

所以你需要使用扁平列表。

如果子列表的repr是其不公平的明确证据,那么你可以这样做:

from collections import OrderedDict
import numpy as np

A = [['foo', 123], ['bar', np.array(range(10))], ['baz', 345]]
B = [['foo', 123], ['bar', np.array(range(10))], ['meow', 456]]

seen=OrderedDict((repr(e),0) for e in B)

newA=[]
for e in A+B:
    key=repr(e)
    if key in seen:
        if seen[key]==0:
            newA.append(e)
            seen[key]=1
    else:
        seen[key]=1
        newA.append(e)

print newA
# [['foo', 123], ['bar', array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])], ['baz', 345], ['meow', 456]]

由于repr函数返回一个字符串,eval函数可以使用该字符串来重新创建列表,这是非常明确的测试,但我不能绝对肯定地说。这取决于你的清单中的内容。

例如,lambda的repr无法重新创建lambda:

>>> repr(lambda x:x)
'<function <lambda> at 0x10710ec08>'

但是'<function <lambda> at 0x10710ec08>'的字符串值仍然是绝对唯一的,因为0x10710ec08部分是lambda内存中的地址(无论如何都在cPython中)。

您也可以执行我上面提到的操作 - 在冻结集中使用展平列表作为您所看到或不看到的签名:

def flatten(LoL):
    for el in LoL:
        if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
            for sub in flatten(el):
                yield sub
        else:
            yield el      
newA=[]    
seen=set()
for e in A+B:
    fset=frozenset(flatten(e))
    if fset not in seen:
        newA.append(e)
        seen.add(fset)

print newA        
# [['foo', 123], ['bar', array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])], ['baz', 345], ['meow', 456]]

因此,如果您在A和B中有奇怪的对象,这些对象都是不可用的和奇怪的,非唯一的repr字符串对象 - 那你就不走运了。举个例子,这些方法中的一个应该可以工作。

答案 1 :(得分:0)

你可以做到

import numpy as np

A = [['foo', 123], ['bar', np.array(range(10))], ['baz', 345]]
B = [['foo', 123], ['bar', np.array(range(10))], ['meow', 456]]

res = set().update(tuple(x) for x in A).update(tuple(x) for x in B)

除了 np.array项目,这些项目是不可取的......不知道如何处理这些项目。