[英]All combinations across multiple lists
給定一個多維列表(列表列表),我想獲得子列表項的所有可能組合。
例如輸入:
my_list = [
['a', 'b'], ['1', '2'], ['@', '&']
]
將導致:
result = [
['a'],
['b'],
['1'],
['2'],
['@'],
['&'],
['a', '1'],
['a', '2'],
['a', '@'],
['a', '&']
['b', '1'],
['b', '2'],
['b', '@'],
['b', '&'],
['a', '1', '@'],
['a', '1', '&'],
['a', '2', '@'],
['a', '2', '&'],
...]
我嘗試使用itertools.product(* list),但這導致所有項目的組合沒有較小的組合集。 看來itertools.combinations,itertools.permutations等並沒有完全滿足我的要求。
有快速的方法嗎?
在這種情況下,您首先要遍歷所有可能的長度。 對於每種長度,請選擇列表的所有可能組合,對於每種組合,請使用itertools.product
:
def weird_product(*data):
for i in range(1,len(data)+1):
for subdata in itertools.combinations(data,i):
for elem in itertools.product(*subdata):
yield elem
這將產生:
>>> list(weird_product(*data))
[('a',), ('b',), ('1',), ('2',), ('@',), ('&',), ('a', '1'), ('a', '2'), ('b', '1'), ('b', '2'), ('a', '@'), ('a', '&'), ('b', '@'), ('b', '&'), ('1', '@'), ('1', '&'), ('2', '@'), ('2', '&'), ('a', '1', '@'), ('a', '1', '&'), ('a', '2', '@'), ('a', '2', '&'), ('b', '1', '@'), ('b', '1', '&'), ('b', '2', '@'), ('b', '2', '&')]
或更精美的格式:
>>> list(weird_product(*data))
[('a',),
('b',),
('1',),
('2',),
('@',),
('&',),
('a', '1'),
('a', '2'),
('b', '1'),
('b', '2'),
('a', '@'),
('a', '&'),
('b', '@'),
('b', '&'),
('1', '@'),
('1', '&'),
('2', '@'),
('2', '&'),
('a', '1', '@'),
('a', '1', '&'),
('a', '2', '@'),
('a', '2', '&'),
('b', '1', '@'),
('b', '1', '&'),
('b', '2', '@'),
('b', '2', '&')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.