替换方法和for循环

时间:2018-08-30 13:02:51

标签: python-3.x

我试图通过反转一个字符串来对DNA序列进行反转录,然后找到其对应的一对(如果出现“ A”,然后用“ T”切换)并返回一个新的字符串,该字符串被“反转录”。循环似乎只能部分工作,而不会进入elif语句。我尝试了两种方法,但遇到了相同的问题:

def structures(seq):
revlist = seq[::-1]
for item in revlist:
    if item == 'A':
        return revlist.replace('A','T',1000)
    elif item == 'T':
        return revlist.replace('T','A',1000)
    elif item == 'G':
        return revlist.replace('G','C',1000)
    elif item == 'C':
        return revlist.replace('C','G',1000)
    else:
        pass

structures('ATTTGCCCTA')

    # below is the second way I'm trying to code it

def structures(seq):
revlist = seq[::-1]
old = ['A','T','G','C']
new = ['T','A','C','G']
for item in revlist:
    if item == 'A':
        return revlist.replace(old[0],new[0])
    elif item == 'T':
        return revlist.replace(old[1],new[1])
    elif item == 'G':
        return revlist.replace(old[2],new[2])
    elif item == 'C':
        return revlist.replace(old[3],new[3])
    else:
        pass    

structures('ATTTGCCCTA')

2 个答案:

答案 0 :(得分:1)

方法str.replace用于将单个子字符串替换为另一个子字符串。请记住,多次调用str.replace效率不高,因为这意味着多次遍历字符串,而一次遍历就足够了。

要翻译字符,您应该使用str.translate

def dna_complement(dna):
    translation = str.maketrans({'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'})
    return dna.translate(translation)[::-1]

print(dna_complement('AGTC'))

输出

GACT

答案 1 :(得分:-1)

def structures(dna):
    revlist = ''
   for item in dna:
    if item == 'A':
        revlist = 'T' + revlist
    elif item == 'C':
        revlist = 'G' + revlist
    elif item == 'G':
        revlist = 'C' + revlist
    elif item == 'T':
        revlist = 'A' + revlist
return revlist

此代码似乎运行良好。我没有反转列表,而是研究了另一种以相反的顺序添加信息的方法,这等同于同一件事。归功于github