Python 2。**从列表列表中查找两个列表组合的所有可能交集的并集

时间:2018-08-05 23:13:22

标签: python union list-comprehension intersection

免责声明:我正在自学Python,因此可能对我的每个问题都有一些简单的解决方案。感谢耐心!

我知道标题不太清楚,因此我将尝试通过示例进行澄清。

假设我们有一系列交易:

txArray=[[u'1'],[u'2'],[u'2', u'3']]

目标是编写一个函数myIntersection(arrayOfLists),该函数首先计算txArray中每个可能的列表对的交集,然后取并集。

因此myIntersection(txArray)应该返回[u'2'],因为:

int1=intersection([u'1'],[u'2'])=[]
int2=intersection([u'1'],[u'2', u'3'])=[]
int3=intersection([u'2'],[u'2', u'3'])=[u'2']

union=(int1 U int2 U int3)=[u'2']

到目前为止我尝试过的是:

from itertools import combinations

'''
Pseudocode:
1) Generate all possible 2-combinations of the lists in txArray
2) Flatten the lists
3) If a value appears more than once in a 2-combination, add it to
list of intersections
4) Keep unique elements in list of intersections

'''

def myIntersection(arrayOfLists):
    flat_list=[]
    intersections=[]
    combs=list(combinations(txArray,2))
    for i in range(0, len(combs)):
        flat_list.append([item for sublist in combs[i] for item in sublist])
    for list in flat_list:
        for element in list:
            if list.count(element)>1:
                if element not in intersections:
                    intersections.append(element)
    return intersections

虽然它可以在python命令行界面中运行,但是当我将其另存为python文件并运行它时,这种方法总是会出错。

我的问题是: 1)当我将其作为python文件运行时,为什么它不起作用?

2)是否有一种更简洁,更“ pythonic”的方式来做到这一点(可能与列表理解有关)

3)我确实考虑过使用集合,但是我想不出将arrayofLists的列表(通常情况下)迭代转换为集合的方法。有一个简单的语法可以做到这一点吗?

非常感谢您!

2 个答案:

答案 0 :(得分:1)

“更多pythonic”解决方案:

import itertools
txArray=[[u'1'],[u'2'],[u'2', u'3']]
# generate all possible pairs from txArray, and intersect them 
ix=[set(p[0]).intersection(p[1]) for p in itertools.combinations(txArray,2)]
# calculate the union of the list of sets
set.union(*ix)

答案 1 :(得分:1)

您可以使用itertools.combinations生成长度2的所有可能组合

In [232]: from itertools import combinations

In [233]: list(combinations(txArray, 2))
Out[233]: [(['1'], ['2']), (['1'], ['2', '3']), (['2'], ['2', '3'])]

然后,您可以将每对列表转换为set,并对它们执行intersection,为您提供一组集合

In [234]: intersections = [set(a).intersection(set(b)) for a, b in combinations(txArray, 2)]

In [235]: intersections
Out[235]: [set(), set(), {'2'}]

最后,您可以对集合集合执行union,以从列表中解压缩所有集合

In [236]: set.union(*intersections)
Out[236]: {'2'}

此外,请注意,与按索引([set(a).intersection(set(b)) for a, b in combinations(txArray, 2)])访问相比,解压缩组合([set(c[0]).intersection(set(c[1])) for c in combinations(txArray, 2)])更加容易faster

相关问题