[英]How to retrieve all possible combinations given a sequence of keys from a dictionary with list values
I have for instance this dictionary 我有这个字典
d={'M':['ATG'],'D':['GAC','GAT'],'E':['GAA','GAG']}
What I'd like to have as an output given a sequence of keys is a list with all possible sequences. 在给定一系列键的情况下,我想要的输出是包含所有可能序列的列表。 (could be a string as well, in which all the possible sequences would be in separate lines "\\n")
(也可以是一个字符串,其中所有可能的序列都在单独的行中“\\ n”)
sequence = "MDE"
So, the output should be the following: 所以,输出应该如下:
['ATGGACGAA','ATGGACGAG','ATGGATGAA','ATGGATGAG']
What I've tried so far is the following, but of course it's not what I want: 到目前为止我所尝试的是以下内容,但当然这不是我想要的:
seq_trans = ''
for aa in sequence:
for k, v in d.iteritems():
if k == aa:
for item in v:
seq_trans= seq_trans + item
print seq_trans
And what I get for "MDE" is: 我得到的“MDE”是:
'ATGGACGATGAAGAG'
You can use itertools.product
here, it returns Cartesian product of the input iterables. 你可以在这里使用
itertools.product
,它返回输入迭代的笛卡尔积。
In [78]: seq="MED"
In [79]: ["".join(x) for x in product(*(d[y] for y in seq))]
Out[79]: ['ATGGAAGAC', 'ATGGAAGAT', 'ATGGAGGAC', 'ATGGAGGAT']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.