python有效地比较列表列表

时间:2013-11-05 13:35:48

标签: python list set

我有很长的长列表,所以效率对我来说是一个问题。我想知道是否有更简洁的方法来比较列表列表而不是循环遍历同一列表的循环中的列表(更容易通过示例看到)

matchList=[]
myList = [ ('a',[1,2,3]), ('b', [2,3,4]), ('c', [3,4,5]), ('d', [4,5,6]) ]

tup_num=1
for tup in myList:
    for tup2 in myList[tup_num:]:
        id=str(tup[0])+':'+str(tup2[0])
        matches=set(tup[1]) & set(tup2[1])
        matchList.append((id,matches))
    tup_num+=1

print matchList

输出:

[('a:b', set([2, 3])), ('a:c', set([3])), ('a:d', set([])), ('b:c', set([3, 4])), ('b:d', set([4])), ('c:d', set([4, 5]))]

这是有效的,不会重复比较,但我确信必须有更好的方法。

干杯

3 个答案:

答案 0 :(得分:2)

使用itertools.combinations

>>> import itertools
>>> matchList = []
>>> myList = [('a',[1,2,3]), ('b', [2,3,4]), ('c', [3,4,5]), ('d', [6,7,8])]
>>> matchList = [
...     ('{}:{}'.format(key1, key2), set(lst1) & set(lst2))
...     for (key1, lst1), (key2, lst2) in itertools.combinations(myList, 2)
... ]
>>> matchList
[('a:b', set([2, 3])), ('a:c', set([3])), ('a:d', set([])), ('b:c', set([3, 4])), ('b:d', set([])), ('c:d', set([]))]

答案 1 :(得分:1)

  • 首先将这些列表转换为集合。这是一个O(n)操作,最好避免使用。
  • itertools.combinations更快更容易。

像这样:

>>> from itertools import combinations
>>> l
[('a', [1, 2, 3]), ('b', [2, 3, 4]), ('c', [3, 4, 5]), ('d', [6, 7, 8])]
>>> l = [(i, set(j)) for i, j in l]
>>> l
[('a', {1, 2, 3}), ('b', {2, 3, 4}), ('c', {3, 4, 5}), ('d', {8, 6, 7})]
>>> [("%s:%s" % (l1[0], l2[0]), l1[1] & l2[1]) for l1, l2 in combinations(l, 2)]
[('a:b', {2, 3}), ('a:c', {3}), ('a:d', set()), ('b:c', {3, 4}), ('b:d', set()), ('c:d', set())]

答案 2 :(得分:1)

使用合成和生成器清楚地表明:

from itertools import combinations

matchList = []
myList = [ ('a',[1,2,3]), ('b', [2,3,4]), ('c', [3,4,5]), ('d', [4,5,6]) ]

def sets(items):
  for name, tuple in items:
    yield name, set(tuple)

def matches(sets):
  for a, b in combinations(sets, 2):
    yield ':'.join([a[0], b[0]]), a[1] & b[1]

print list(matches(sets(myList)))


>>> [('a:b', set([2, 3])), ('a:c', set([3])), ('a:d', set([])), ('b:c', set([3, 4])), ('b:d', set([4])), ('c:d', set([4, 5]))]