簡體   English   中英

Python 2。**從列表列表中查找兩個列表組合的所有可能交集的並集

[英]Python 2.** Finding the union of all possible intersections of two-list combinations from a list of lists

免責聲明:我正在自學Python,因此可能對我的每個問題都有一些簡單的解決方案。 感謝耐心!

我知道標題不太清楚,因此我將嘗試通過一個例子進行說明。

假設我們有一系列交易:

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

目標是編寫一個函數myIntersection(arrayOfLists) ,該函數首先計算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的列表(通常情況下)迭代轉換為集合的方法。 有一個簡單的語法可以做到這一點嗎?

非常感謝!

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

您可以使用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)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM