如何在列表列表中的对之间获取所有特定大小的唯一联合?

How to get all unique unions of specific size between pairs in a list of lists?

我有一个列表 L,其中每个元素都是一个大小为 n 的列表。我试图在 L 中的每对列表之间找到所有大小为 n+1 的唯一“联合”。例如,让 unique_unions_n(L,n) 成为执行我想要的功能的函数

L = [['a','c'],
    ['b','c'],
    ['b','e'],
    ['c','e']]
n = 2
unique_unions_k(L, n) -> [['a', 'b', 'c'], ['e', 'a', 'c'], ['e', 'c', 'b']]

注意,['a','c'] union ['b','e'] 不包括在内,因为它的并集(['a','b','c','e'] 的大小大于 n+1

这是我想出的,它在 L 中的列表对的所有组合之间生成大小为 n+1 的并集,但这并不能保证并集是“唯一的”。

import itertools
def union(list1, list2):
  return list(set(list1) | set(list2))

def unique_unions_n(L, n):
  result = []
  for item in itertools.combinations(L, 2):
    u = union(item[0], item[1])
    if len(u) == n+1:
      result.append(u)
  return result

当在上面的示例中给出相同的列表 L 时,我的尝试生成

result = [['a', 'b', 'c'],
 ['e', 'a', 'c'],
 ['e', 'c', 'b'],
 ['e', 'c', 'b'],
 ['c', 'e', 'b']]

这是不可取的,因为我认为 ['e','c','b']['c','e','b'] 不是唯一的。我知道我的功能失败是因为我正在查看每个组合。对于更大的列表,我也试图以最有效的方式做到这一点。我错过了什么?

(除了通过示例,我不确定如何 ask/title 这个问题,所以如果有人有更好的标题方式请告诉我!)

尝试使用集合来消除重复项:

import itertools

def unique_unions_n(L, n):
  result = set()
  for item in itertools.combinations(L, 2):
    u = frozenset(item[0] + item[1])
    if len(u) == n+1:
      result.add(u)
  return result

L = [['a','c'],
    ['b','c'],
    ['b','e'],
    ['c','e']]
n = 2
print(unique_unions_n(L, n))
# {frozenset({'b', 'e', 'c'}), frozenset({'c', 'a', 'e'}), frozenset({'c', 'a', 'b'})}

如果您需要不同的输出格式,您可以轻松转换为 lists/tuples.

的列表

只需在代码末尾添加这些行:

res=[sorted(i) for i in result]
m=[]
for k in res:
    if k not in m:
        m.append(k)

def unique_lists(listSet):
    res = [sorted(i) for i in listSet]
    outList = []
    for i in res:
        if i not in outList:
            outList.append(i)
    return outList

def unique_unions_k(L, n):
    k = []
    for x in range(0,len(L)):
        for y in range(x, len(L)):
            unique_set = set(L[x]).union(set(L[y]))
            if len(unique_set) == n+1:
                k.append(list(unique_set))

    return unique_lists(k)

# inputs
n = 2
L = [['a','c'],
    ['b','c'],
    ['b','e'],
    ['c','e']]

print(unique_unions_k(L,n))
# [['a', 'b', 'c'], ['a', 'c', 'e'], ['b', 'c', 'e']]