我想把這個(gè)序列分成一個(gè) n=3 的列表。codons('agucaccgucautc')# result = ['agu','cac','cgu','cau']# 'tc' is supposed to be ignored as it doesn't equal to n=3我嘗試過以下解決方案;def codons(RNA): """This functions returns a list of codons present in an RNA sequence""" # store the length of string length = len(RNA) #divide the string in n equal parts n = 3 temp = 0 chars = int(len(RNA)/3) #stores the array of string change = [] #check whether a string can be divided into n equal parts for i in range(0, length, chars): part = [RNA[i:i+3] for i in range(0, length, n)]; change.append(part); return part if (length % n != 0): continue但是當(dāng)我嘗試再次運(yùn)行之前的代碼時(shí),它仍然返回“tc”codons('agucaccgucautc')# result = ['agu', 'cac', 'cgu', 'cau', 'tc']誰能幫我做什么來忽略任何不等于 n=3 或最后一部分“tc”的字符?
1 回答

波斯汪
TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以按以下方式使用列表理解:
s = 'agucaccgucautc'
n = 3
out = [(s[i:i+n]) for i in range(0, len(s), n) if len(s[i:i+n])%n == 0]
添加回答
舉報(bào)
0/150
提交
取消