python有效地比较列表列表 [英] python compare a list of lists efficiently

查看:82
本文介绍了python有效地比较列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的清单很长,因此效率对我来说是个问题.我想知道是否有一种比较整洁的方式来比较列表列表,而不是在同一个列表的循环中遍历列表(更易于查看示例)

I have a long list of long lists so efficiency is an issue for me. I wondered if there was a neater way of comparing a list of lists other than looping over a list within a loop of the same list (easier to see by example)

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]))]

这有效,并且不会重复比较,但是我敢肯定必须有更好的方法.

This works and doesn't repeat comparisons but I'm sure there must be a better way of doing it.

欢呼

推荐答案

使用 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([]))]

这篇关于python有效地比较列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆