簡體   English   中英

從兩個列表中查找不同的組合

[英]Find different combinations from two lists

給定兩個任意長度的列表,我想找到兩個列表之間的所有可能組合,然后在新列表中添加一個組合的字典對。

例如,這兩個列表是:

List1 - ['A', 'B']

List2 2 - [1, 2]

結果列表應具有以下值:

[{'A':1, 'B':1}, {'A':1,'B':2}, {'A':2, 'B':1}, {'A':2, 'B':2}]

我發現的所有解決方案都只是給出了可能的組合。 所以,假設我有一個長度為 3 和 2 的列表。可能的組合只有 6 個值。 但是,根據我的要求,會有 8 個值。

我使用的代碼:

first_list = ['A', 'B', 'C'] 
second_list = [1, 2]
 
combinations = [(a,b) for a in first_list for b in second_list]

其中 output 如下:

[('A', 1), ('A', 2), ('B', 1), ('B', 2), ('C', 1), ('C', 2)]

雖然我想要的 output 是:

[{'A':1, 'B':1, 'C':1},
 {'A':1, 'B':1, 'C':2},
 {'A':1, 'B':2, 'C':1},
 {'A':1, 'B':2, 'C':2},
 {'A':2, 'B':1, 'C':1},
 {'A':2, 'B':1, 'C':2},
 {'A':2, 'B':2, 'C':1},
 {'A':2, 'B':2, 'C':2}]

您可以使用itertools.product創建部分組合:

from itertools import product

first_list = ['A', 'B', 'C'] 
second_list = [1, 2]

out = product(second_list, repeat=len(first_list))

combinations = [{f:s for (f,s) in zip(first_list, c)} for c in out]

print(combinations)

Output 根據需要。

你應該抬頭看這里

您可以使用

list1 = ["a", "b", "c"]
list2 = [1, 2]
all_combinations = []

list1_permutations = itertools.permutations(list1, len(list2))
Get all permutations of `list1` with length 2

for each_permutation in list1_permutations:
    zipped = zip(each_permutation, list2)
    all_combinations.append(list(zipped))

print(all_combinations)

Output

[[('a', 1), ('b', 2)], [('a', 1), ('c', 2)], [('b', 1), ('a', 2)], [('b', 1), ('c', 2)], [('c', 1), ('a', 2)], [('c', 1), ('b', 2)]]

暫無
暫無

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

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