简体   繁体   中英

Python .split list is callable but index is out of range?

I am writing a code to translate DNA and am looking for some help.

A sample input would look like:ACGTGC

and I'm looking for the output to be:["T","G","C","A","C","G"]

I also would like for the while loop to loop only as many times as the amount of characters in the input.(replace the 9 with a variable)

I am very thankful for all help!

n = 0
i = 0
list_1 = []
text = raw_input("TYPE WITH SPACES BETWEEN LETTERS:")
hi = len(text)
while i < 9 : 
    split_string = text.split(" ")
    if split_string[n] == "A" : 
        list_1.append("T")
    elif split_string[n] == "T" :
        list_1.append("A")
    elif split_string[n] == "C" :
        list_1.append("G")
    elif split_string[n] == "G" :
        list_1.append("C")
    i = i +1
    n = n + 1
print list_1

How about just using split() to break up the input in one go:

>>> dnaSeq = raw_input("Enter a space-separated DNA string:").split()
Enter a space-separated DNA string:A C G T G C
>>> dnaSeq
['A', 'C', 'G', 'T', 'G', 'C']

And then use a dictionary that maps bases to their base pair to get the complementary strand:

>>> dnaPair = dict(A="T", T="A", C="G", G="C")
>>> complement = [dnaPair[base] for base in dnaSeq]
>>> complement
['T', 'G', 'C', 'A', 'C', 'G']

This should do it.

translate_dict={'A':'T',
        'T':'A',
        'C':'G',
        'G':'C'}
text=raw_input("TYPE WITH SPACES BETWEEN LETTERS:")
print [translate_dict[item] for item in text.upper().split(' ')]

Result:

TYPE WITH SPACES BETWEEN LETTERS:A T G G C C G T C
['T', 'A', 'C', 'C', 'G', 'G', 'C', 'A', 'G']

A one-liner in python 3

text.translate(str.maketrans('ATCG','TAGC')).split(' ')

or even

raw_input('Type with spaces between  letters:'
).translate(str.maketrans('ATCG','TAGC')).split(' ')

or in Python 2

from string import maketrans
text.translate(maketrans('ATCG','TAGC')).split(' ')

Listening to everybody, I think I worked it out. I don't have enough reputation to up vote, but I would!!! (I also coded for Uracil and its "transcribed", not "translated". Thanks!

conv={"A":"T","T":"A","C":"G","G":"C","U":"A"}

outputDNA=""
inputDNA= raw_input("Type the DNA sequence you want transcribed: ")

for letter in inputDNA:
    outputDNA += conv[letter]
print outputDNA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM