Не самое эффективное решение, но оно даст желаемый результат и будет работать с увеличением максимальных размеров кортежей:
s = [(), (1,), (1,1), (1,2), (2,), (2,1,1), (2,1,2), (2,2)]
def tupleSameGroup(tuple1, tuple2, sameGroup=True):
if any(tuple1[idx]!=tuple2[idx] for idx in range(len(tuple1))):
return False
return sameGroup
groups = [[i, j] for i in s for j in [x for x in s if len(x)>len(i)] if tupleSameGroup(i, j)]
Выход:
[[(), (1,)], [(), (1, 1)], [(), (1, 2)], [(), (2,)], [(), (2, 1, 1)], [(), (2, 1, 2)], [(), (2, 2)], [(1,), (1, 1)], [(1,), (1, 2)], [(2,), (2, 1, 1)], [(2,), (2, 1, 2)], [(2,), (2, 2)]]
Затем вы можете комбинировать этигруппировать вместе на основе общих элементов:
combined_groups = [sorted(list(set(i) | set(j))) for i in groups for j in groups if i[-1] in j and i!=j]
Выход:
[[(), (1,), (1, 1)], [(), (1,), (1, 2)], [(), (1,), (1, 1)], [(), (1,), (1, 2)], [(), (2,), (2, 1, 1)], [(), (2,), (2, 1, 2)], [(), (2,), (2, 2)], [(), (2,), (2, 1, 1)], [(), (2,), (2, 1, 2)], [(), (2,), (2, 2)], [(), (1,), (1, 1)], [(), (1,), (1, 2)], [(), (2,), (2, 1, 1)], [(), (2,), (2, 1, 2)], [(), (2,), (2, 2)]]
Наконец, мы можем создать новый список без дубликатов:
no_duplicates = []
for i in combined_groups:
if i not in no_duplicates:
no_duplicates.append(i)
Выход:
[[(), (1,), (1, 1)],
[(), (1,), (1, 2)],
[(), (2,), (2, 1, 1)],
[(), (2,), (2, 1, 2)],
[(), (2,), (2, 2)]]