![](/img/trans.png)
[英]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.