簡體   English   中英

如何獲得對索引有限制的對列表的所有組合

[英]How to get all the combinations of a list of pairs with a restriction on indices

我最初有兩個數字列表,但對於這種情況,假設我有一個元組列表,我想獲得所有可能的組合,使得 output 具有索引 0 中第一對的成員,第二對中的一個索引 1 中的對等

例如,讓列表為: [(1, 2), (3, 4), (5,6)]

我想得到:

1, 3, 5
1, 3, 6
1, 4, 5
1, 4, 6
2, 3, 5
2, 3, 6
2, 4, 5
2, 4, 6

該列表可以是任意長度。 我嘗試在兩個原始列表上使用itertools.permutations ,如下所示: [list(zip(permutation, list2)) for permutation in itertools.permutations(list1, len(list2))]

但它會返回所有可能的排列,這不是我需要的。

這可以通過香草廣度優先搜索/深度優先搜索來完成:

a = [(1, 2), (3, 4), (5,6)]

def search(points):
    points = list(points)
    paths = []
    if points:
        first_points = points.pop(0)
    else:
        return [[]]
    for point in first_points:
        for path in bfs(points):
            paths.append([point] + path)
    
    return paths

print(search(a))

退貨:

[1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6], [2, 3, 5], [2, 3, 6], [2, 4, 5], [2, 4, 6]]

現在,我匆忙地寫了這個,它不是最有效的代碼,但它會完成工作

暫無
暫無

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

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