[英]Generate all permutations of a list and permutations of the possible lists within that list?
[英]Generate permutations of a list of lists with variable lengths
我希望生成所有可能的字符組合,其中字符列表中的每個位置可能有也可能沒有多個選擇。
例如,如果我有列表[['A','G'],['A','C','G'],'T']
我想從列表中生成['AAT','ACT','AGT','GAT','GCT','GGT']
。 最好的方法是什么? 我過去曾使用過itertools,但我看不到任何功能如何處理這種請求。
使用itertools.product()
:
from itertools import product
lsts = [['A', 'G'], ['A', 'C', 'G'], 'T']
output = [''.join(combo) for combo in product(*lsts)]
的*lsts
語法適用於每個元素lsts
作為單獨的參數的products()
的功能; 就像您調用product(['A', 'G'], ['A', 'C', 'G'], 'T')
。
演示:
>>> from itertools import product
>>> lsts = [['A','G'],['A','C','G'],'T']
>>> [''.join(combo) for combo in product(*lsts)]
['AAT', 'ACT', 'AGT', 'GAT', 'GCT', 'GGT']
您可以將嵌套列表簡化為相同輸出的字符串:
lsts = ['AG', 'ACG','T']
或者,為了保持一致性,使最后一個元素成為列表:
lsts = [['A', 'G'], ['A', 'C', 'G'], ['T']]
但它也適用於混合序列。
首先,您應使用['T']
而不是'T'
使列表(列表列表)同質
>>> import itertools
>>> L = [['A','G'],['A','C','G'],['T']]
>>> [''.join(x) for x in itertools.product(*L)]
['AAT', 'ACT', 'AGT', 'GAT', 'GCT', 'GGT']
迭代字符串'T'
也可以,但是可能會導致其他錯誤
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.