免责声明:我正在自学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列表(一般情况下)转换为集合。有没有一种简单的语法可以做到这一点?
非常感谢!
发布于 2018-08-06 07:29:39
一种“更具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)
发布于 2018-08-06 07:29:48
您可以使用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)]
)更具可读性。
https://stackoverflow.com/questions/51698925
复制相似问题