簡體   English   中英

從列表列表中生成值的組合python

[英]Generating combinations of values from a list of lists python

我想獲取列表列表的組合,例如

[['a0', 'a1'], ['b0', 'b1'], ['c0', 'c1', 'c2']]

我可以使用list(itertools.product(*listOfTuples))並獲取

[('a0', 'b0', 'c0'), ('a0', 'b0', 'c1'), ('a0', 'b0', 'c2')... ('a1', 'b1', 'c2')]

如何獲得長度為2的可能組合的列表? 例如:

[('a0', 'b0'), ('a0', 'c0'), ('b0', 'c0')...

您可以僅使用r=2調用itertools.combinations()來獲取每個三元組的所有對,然后進行展平,例如:

In []:
import itertools as it
[t for x in it.product(*s) for t in it.combinations(x, r=2)]

Out[]:
[('a0', 'b0'), ('a0', 'c0'), ('b0', 'c0'), ('a0', 'b0'), ('a0', 'c1'), ('b0', 'c1'),
 ('a0', 'b0'), ('a0', 'c2'), ('b0', 'c2'), ('a0', 'b1'), ('a0', 'c0'), ('b1', 'c0'), 
 ('a0', 'b1'), ('a0', 'c1'), ('b1', 'c1'), ('a0', 'b1'), ('a0', 'c2'), ('b1', 'c2'), 
 ('a1', 'b0'), ('a1', 'c0'), ('b0', 'c0'), ('a1', 'b0'), ('a1', 'c1'), ('b0', 'c1'), 
 ('a1', 'b0'), ('a1', 'c2'), ('b0', 'c2'), ('a1', 'b1'), ('a1', 'c0'), ('b1', 'c0'), 
 ('a1', 'b1'), ('a1', 'c1'), ('b1', 'c1'), ('a1', 'b1'), ('a1', 'c2'), ('b1', 'c2')]

但是,由於('a0', 'b0', 'c0')('a0', 'b0', 'c1')('a0', 'b0', 'c2')全部generate ('a0', 'b0') ,因此,如果要刪除,則可以使用set ,但是會丟失順序:

In []:
{t for x in it.product(*s) for t in it.combinations(x, r=2)}

Out[]:
{('a1', 'c0'), ('b0', 'c1'), ('b0', 'c2'), ('a0', 'c1'), ('a0', 'c2'), ('b1', 'c1'), 
 ('b1', 'c2'), ('a1', 'b1'), ('a1', 'c1'), ('a1', 'c2'), ('b0', 'c0'), ('a0', 'c0'), 
 ('a1', 'b0'), ('b1', 'c0'), ('a0', 'b1'), ('a0', 'b0')}

對其進行排序確實將其放回了順序:

In []:
sorted({t for x in it.product(*s) for t in it.combinations(x, r=2)})

Out[]:
[('a0', 'b0'), ('a0', 'b1'), ('a0', 'c0'), ('a0', 'c1'), ('a0', 'c2'), ('a1', 'b0'), 
 ('a1', 'b1'), ('a1', 'c0'), ('a1', 'c1'), ('a1', 'c2'), ('b0', 'c0'), ('b0', 'c1'), 
 ('b0', 'c2'), ('b1', 'c0'), ('b1', 'c1'), ('b1', 'c2')]

您可以展平列表,並創建一個簡單的遞歸函數(用於子列表中沒有重復的結果):

d = [['a0', 'a1'], ['b0', 'b1'], ['c0', 'c1', 'c2']]
def combinations(d, current = []):
  if len(current) == 2:
    yield current
  else:
    for i in d:
      if i not in current:
        yield from combinations(d, current+[i])

print(list(combinations([i for b in d for i in b]))

輸出:

[['a0', 'a1'], ['a0', 'b0'], ['a0', 'b1'], ['a0', 'c0'], ['a0', 'c1'], ['a0', 'c2'], ['a1', 'a0'], ['a1', 'b0'], ['a1', 'b1'], ['a1', 'c0'], ['a1', 'c1'], ['a1', 'c2'], ['b0', 'a0'], ['b0', 'a1'], ['b0', 'b1'], ['b0', 'c0'], ['b0', 'c1'], ['b0', 'c2'], ['b1', 'a0'], ['b1', 'a1'], ['b1', 'b0'], ['b1', 'c0'], ['b1', 'c1'], ['b1', 'c2'], ['c0', 'a0'], ['c0', 'a1'], ['c0', 'b0'], ['c0', 'b1'], ['c0', 'c1'], ['c0', 'c2'], ['c1', 'a0'], ['c1', 'a1'], ['c1', 'b0'], ['c1', 'b1'], ['c1', 'c0'], ['c1', 'c2'], ['c2', 'a0'], ['c2', 'a1'], ['c2', 'b0'], ['c2', 'b1'], ['c2', 'c0'], ['c2', 'c1']]

暫無
暫無

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

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