对于内部列表,将字符串分解为3个字符的首字母缩写


def testing(dnaStrand):

protein = []
start = dnaStrand.find('ATG')

end = len(dnaStrand)

totalLength = dnaStrand[start:end]

remove = totalLength.split('TAG')

protein = [[i] for i in remove]

print(protein)
protein is a list of lists - Each time 'TAG' appears in the given string a new inner list is created and contains all characters up till the next 'TAG'. I want my inner lists to be groups of three characters. For example:
testing('ATGABCTAGDEFHIJTAGKLM')
returns:
[['ATGABC'], ['DEFHIJ'], ['KLM']]
What I need:
[['ATG', 'ABC'], ['DEF', 'HIJ'], ['KLM']]

输入可以是字母的任何组合,可以有无限的内部列表,内部列表中可以有无限个项目。

您可以使用列表理解,请尝试以下操作:

def testing(dnaStrand):
protein = []
start = dnaStrand.find('ATG')
end = len(dnaStrand)
totalLength = dnaStrand[start:end]
remove = totalLength.split('TAG')
for str in remove:
split_str = [str[i:i+3] for i in range(0, len(str), 3)]
protein.append(split_str)    
print(protein)
testing('ATGABCTAGDEFHIJTAGKLM')

试试这个:

def testing(dnaStrand):
protein = []
start = dnaStrand.find('ATG')
end = len(dnaStrand)
totalLength = dnaStrand[start:end]
remove = totalLength.split('TAG')
for i in remove: # every item in remove
appendlist = [i[:3],i[3:]] # split with 3 chars
if appendlist[1] == '': # if the item is empty, 
del appendlist[1] # delete it
protein.append(appendlist) # then append it to protein
print(protein)
testing('ATGABCTAGDEFHIJTAGKLM')

试试这个

def testing(dnaStrand):
protein=dnaStrand.split('TAG')
for i in range(len(protein)):
if len(protein[i]) > 3:
protein[i]=[protein[i][:3],protein[i][3:]]
else:
protein[i]=[protein[i][:3]]
print(protein)
testing('ATGABCTAGDEFHIJTAGKLM')

编辑:

def testing(dnaStrand):
protein=dnaStrand.split('TAG')
for i in range(len(protein)):
if len(protein[i]) > 3:
protein[i]=[protein[i][:3],protein[i][3:]]
else:
protein[i]=[protein[i][:3]]
return protein
print(testing('ATGABCTAGDEFHIJTAGKLM'))

输出

>>> [['ATG', 'ABC'], ['DEF', 'HIJ'], ['KLM']]

最新更新