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

2024-07-02 10:17:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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']]

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


Tags: oftheinistagtestingstartlists
3条回答

您可以使用列表理解,请尝试以下方法:

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=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']]

试试这个:

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')

相关问题 更多 >