【问题标题】:Python 2.** Finding the union of all possible intersections of two-list combinations from a list of listsPython 2.** 从列表列表中查找两个列表组合的所有可能交集的并集
【发布时间】:2018-08-05 23:13:21
【问题描述】:

免责声明:我正在自学 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 列表(在一般情况下)迭代转换为集合。是否有一个简单的语法来做到这一点?

非常感谢!

【问题讨论】:

  • “我不断收到错误”是不充分的描述

标签: python union list-comprehension intersection


【解决方案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'}

另外,请注意faster 和解压组合 ([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)]) 更具可读性

【讨论】:

  • 这非常有帮助,谢谢!虽然这行得通,但我选择了@tif 提供的答案,因为它更短、更简洁,而且更多的是我正在寻找的“pythonic”。非常感谢!
  • 答案完全一样。我的只是一个解释
【解决方案2】:

一个“更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)

【讨论】:

  • 这正是我正在寻找的'pythonic',谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-25
  • 1970-01-01
相关资源
最近更新 更多