[英]Python - multiple combinations maths question
I'm trying to make a program that lists all the 64 codons/triplet base sequences of DNA... In more mathematical terms, there are 4 letters: A, T, G and C.我正在尝试编写一个程序,列出 DNA 的所有 64 个密码子/三联体碱基序列……用更数学的术语来说,有 4 个字母:A、T、G 和 C。
I want to list all possible outcomes where there are three letters of each and a letter can be used multiple times but I have no idea how!我想列出所有可能的结果,每个结果都有三个字母,一个字母可以多次使用,但我不知道怎么做!
I know there are 64 possibilities and I wrote them all down on paper but I want to write a program that generates all of them for me instead of me typing up all 64!我知道有 64 种可能性,我把它们都写在纸上,但我想写一个程序来为我生成所有这些,而不是我把所有 64 种都打出来!
Currently, I am at this point but I have most surely overcomplicated it and I am stuck:目前,我处于这一点,但我肯定把它复杂化了,我被卡住了:
list = ['A','T','G','C']
list2 = []
y = 0
x = 1
z = 2
skip = False
back = False
for i in range(4):
print(list[y],list[y],list[y])
if i == 0:
skip = True
else:
y=y+1
for i in range(16):
print(list[y],list[y],list[x])
print(list[y],list[x], list[x])
print(list[y],list[x], list[y])
print(list[y],list[x], list[z])
if i == 0:
skip = True
elif z == 3:
back = True
x = x+1
elif back == True:
z = z-1
x = x-1
else:
x = x+1
z = z+1
Any help would be much appreciated!!!!任何帮助将非常感激!!!!
You should really be using itertools.product
for this.您真的应该为此使用itertools.product
。
from itertools import product
l = ['A','T','G','C']
combos = list(product(l,repeat=3 ))
# all 64 combinations
Since this produces an iterator, you don't need to wrap it in list()
if you're just going to loop over it.由于这会生成一个迭代器,因此如果您只是要循环遍历它,则无需将其包装在list()
。 (Also, don't name your list list
— it clobbers the build-in). (另外,不要命名您的列表list
- 它会破坏内置)。
If you want a list of strings you can join()
them as John Coleman shows in a comment under your question.如果你想要一个字符串列表,你可以join()
它们,正如约翰科尔曼在你的问题下的评论中显示的那样。
list_of_strings = ["".join(c) for c in product(l,repeat=3) ]
Look for for pemuations with repetitions there tons of code available for Python .寻找重复的排列,那里有大量可用于 Python 的代码。 I would just use library , if you want to see how they implemented it look inside the library .如果你想看看他们是如何实现它的,我会使用 library 。 These guys usually do it very efficiency这些家伙通常做得非常有效率
import itertools
x = [1, 2, 3, 4, 5, 6]
[p for p in itertools.product(x, repeat=2)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.