我有一個這樣的清單..
[
[
("a", 1)
] ,
[
("b", 2)
],
[
("c", 3),
("d", 4)
],
[
("e", 5),
("f", 6),
("g", 7)
]
]
我正在嘗試從此串列資料中獲取所有可能的組合。
我的預期輸出應如下所示。
[
[
("a", 1),
("b", 2),
("c", 3),
("e", 5)
],
[
("a", 1),
("b", 2),
("c", 3),
("f", 6)
],
[
("a", 1),
("b", 2),
("c", 3),
("g", 7)
],
[
("a", 1),
("b", 2),
("d", 4),
("e", 5)
],
[
("a", 1),
("b", 2),
("d", 4),
("f", 6)
],
[
("a", 1),
("b", 2),
("d", 4),
("g", 7)
],
]
我嘗試使用 itertools.combinations 但無法獲得預期的輸出,不確定我缺少什么,找不到邏輯,請提供幫助。提前致謝。
如果您需要任何其他資訊,請告訴我,
提前致謝,
uj5u.com熱心網友回復:
你想要itertools.product,沒有itertools.combinations。每個元組串列都應該是 的一個引數product,因此請使用*運算子將起始串列的每個元素作為引數傳遞:
>>> import itertools
>>> list(itertools.product(*lists_of_tuples))
[(('a', 1), ('b', 2), ('c', 3), ('e', 5)), (('a', 1), ('b', 2), ('c', 3), ('f', 6)), (('a', 1), ('b', 2), ('c', 3), ('g', 7)), (('a', 1), ('b', 2), ('d', 4), ('e', 5)), (('a', 1), ('b', 2), ('d', 4), ('f', 6)), (('a', 1), ('b', 2), ('d', 4), ('g', 7))]
uj5u.com熱心網友回復:
如果您真的想使用組合并獲得顯示的輸出格式,您可以執行類似的操作
from itertools import combinations
input_list = [
[("a", 1)],
[("b", 2)],
[("c", 3), ("d", 4)],
[("e", 5), ("f", 6), ("g", 7)],
]
list_for_combos = [i[n] for i in input_list for n, _ in enumerate(i)]
combos = list(
[combo[n] for n, _ in enumerate(combo)]
for combo in combinations(list_for_combos, 4)
)
uj5u.com熱心網友回復:
我認為 itertools.products()
也應該可以作業,因為您希望將結果作為 2d 串列,這應該可以正常作業。
[list(x) for x in itertools.product(*li)] # li is your list
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/407309.html
標籤:
