[英]Generate permutations of a list of lists with variable lengths
I am looking to generate all of the possible combinations of characters where each position in the list of characters may or may not have multiple choices. 我希望生成所有可能的字符组合,其中字符列表中的每个位置可能有也可能没有多个选择。
For example, if I have the list [['A','G'],['A','C','G'],'T']
I would like to generate from it ['AAT','ACT','AGT','GAT','GCT','GGT']
. 例如,如果我有列表
[['A','G'],['A','C','G'],'T']
我想从列表中生成['AAT','ACT','AGT','GAT','GCT','GGT']
。 What is the best way to go about this? 最好的方法是什么? I have used itertools in the past but I don't see how any of the functions can handle this sort of request.
我过去曾使用过itertools,但我看不到任何功能如何处理这种请求。
Use itertools.product()
: 使用
itertools.product()
:
from itertools import product
lsts = [['A', 'G'], ['A', 'C', 'G'], 'T']
output = [''.join(combo) for combo in product(*lsts)]
The *lsts
syntax applies each element in lsts
as a separate argument to the products()
function; 的
*lsts
语法适用于每个元素lsts
作为单独的参数的products()
的功能; as if you called product(['A', 'G'], ['A', 'C', 'G'], 'T')
. 就像您调用
product(['A', 'G'], ['A', 'C', 'G'], 'T')
。
Demo: 演示:
>>> from itertools import product
>>> lsts = [['A','G'],['A','C','G'],'T']
>>> [''.join(combo) for combo in product(*lsts)]
['AAT', 'ACT', 'AGT', 'GAT', 'GCT', 'GGT']
You could reduce your nested lists to strings for the same output: 您可以将嵌套列表简化为相同输出的字符串:
lsts = ['AG', 'ACG','T']
or, for consistency's sake, make the last element a list: 或者,为了保持一致性,使最后一个元素成为列表:
lsts = [['A', 'G'], ['A', 'C', 'G'], ['T']]
but it'll work with the mixed sequences too. 但它也适用于混合序列。
First, you should make your list homogeneous (list of lists) by using ['T']
instead of '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']
Iterating the string 'T'
does also work, but it's likely to cause other bugs in my experience 迭代字符串
'T'
也可以,但是可能会导致其他错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.